Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refact: mock #620

Merged
merged 3 commits into from
Jun 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/guide/env-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,11 @@ $ ESLINT=none umi dev
### BABELRC

开启 `.babelrc` 解析,默认不解析。

### MOCK

默认开启 mock,值为 none 时禁用。比如:

```bash
$ MOCK=none umi dev
```
2 changes: 1 addition & 1 deletion packages/umi-build-dev/src/getPlugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ Try:
'./plugins/antd',
'./plugins/fastclick',
'./plugins/hd',
'./plugins/mock',
'./plugins/proxy',
...(process.env.MOCK === 'none' ? [] : ['./plugins/mock']),
'./plugins/hash-history',
'./plugins/afwebpack-config',
'./plugins/404', // 404 must after mock
Expand Down
195 changes: 0 additions & 195 deletions packages/umi-build-dev/src/plugins/mock/HttpMock.js

This file was deleted.

145 changes: 145 additions & 0 deletions packages/umi-build-dev/src/plugins/mock/createMockMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { existsSync } from 'fs';
import { join } from 'path';
import bodyParser from 'body-parser';
import glob from 'glob';
import assert from 'assert';
import chokidar from 'chokidar';

const VALID_METHODS = ['get', 'post', 'pust', 'delete'];

export default function getMockMiddleware(api) {
const { debug } = api.utils;
const { cwd } = api.service;
const absMockPath = join(cwd, 'mock');
const absConfigPath = join(cwd, '.umirc.mock.js');
api.registerBabel([absMockPath, absConfigPath]);

let mockData = getConfig();
watch();

function watch() {
if (process.env.WATCH_FILES === 'none') return;
const watcher = chokidar.watch([absConfigPath, absMockPath], {
ignoreInitial: true,
});
watcher.on('all', (event, file) => {
debug(`[${event}] ${file}, reload mock data`);
mockData = getConfig();
});
}

function getConfig() {
cleanRequireCache();
let ret = null;
if (existsSync(absConfigPath)) {
debug(`load mock data from ${absConfigPath}`);
ret = require(absConfigPath); // eslint-disable-line
} else {
const mockFiles = glob.sync('**/*.js', {
cwd: absMockPath,
});
debug(
`load mock data from ${absMockPath}, including files ${JSON.stringify(
mockFiles,
)}`,
);
ret = mockFiles.reduce((memo, mockFile) => {
memo = {
...memo,
...require(join(absMockPath, mockFile)), // eslint-disable-line
};
return memo;
}, {});
}
return normalizeConfig(ret);
}

function parseKey(key) {
let method = 'get';
let path = key;
if (key.indexOf(' ') > -1) {
const splited = key.split(' ');
method = splited[0].toLowerCase();
path = splited[1]; // eslint-disable-line
}
assert(
VALID_METHODS.includes(method),
`Invalid method ${method} for path ${path}, please check your mock files.`,
);
return {
method,
path,
};
}

function createHandler(method, path, handler) {
return function(req, res, next) {
if (method === 'post') {
bodyParser.json({ limit: '5mb', strict: false })(req, res, () => {
bodyParser.urlencoded({ limit: '5mb', extended: true })(
req,
res,
() => {
sendData();
},
);
});
} else {
sendData();
}

function sendData() {
if (typeof handler === 'function') {
handler(req, res, next);
} else {
res.json(handler);
}
}
};
}

function normalizeConfig(config) {
return Object.keys(config).reduce((memo, key) => {
const handler = config[key];
const type = typeof handler;
assert(
type === 'function' || type === 'object',
`mock value of ${key} should be function or object, but got ${type}`,
);
const { method, path } = parseKey(key);
memo.push({
method,
path,
handler: createHandler(method, path, handler),
});
return memo;
}, []);
}

function cleanRequireCache() {
Object.keys(require.cache).forEach(file => {
if (file === absConfigPath || file.indexOf(absMockPath) > -1) {
delete require.cache[file];
}
});
}

function matchMock(req) {
const { path: exceptPath } = req;
const exceptMethod = req.method.toLowerCase();

return mockData.filter(({ method, path }) => {
return method === exceptMethod && path === exceptPath;
})[0];
}

return (req, res, next) => {
const match = matchMock(req);
if (match) {
debug(`mock matched: [${match.method}] ${match.path}`);
return match.handler(req, res, next);
} else {
return next();
}
};
}
10 changes: 4 additions & 6 deletions packages/umi-build-dev/src/plugins/mock/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import HttpMock from './HttpMock';
import createMockMiddleware from './createMockMiddleware';

export default function(api) {
api.register('beforeServerWithApp', ({ args: { app } }) => {
new HttpMock({
app,
cwd: api.service.cwd,
api,
});
if (process.env.MOCK !== 'none') {
app.use(createMockMiddleware(api));
}
});
}