Skip to content

Commit

Permalink
Merge pull request #630 from umijs/fix/mock-params
Browse files Browse the repository at this point in the history
fix(umi-build-dev): dynamic param don't work with mock
  • Loading branch information
sorrycc authored Jun 14, 2018
2 parents 7d3cdce + 70889f8 commit 329e5bc
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/umi-build-dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"mkdirp": "^0.5.1",
"object-assign": "^4.1.1",
"path-is-absolute": "^1.0.1",
"path-to-regexp": "^1.7.0",
"postcss-plugin-px2rem": "^0.7.0",
"preact": "^8.2.5",
"preact-compat": "^3.17.0",
Expand Down
49 changes: 47 additions & 2 deletions packages/umi-build-dev/src/plugins/mock/createMockMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import bodyParser from 'body-parser';
import glob from 'glob';
import assert from 'assert';
import chokidar from 'chokidar';
import pathToRegexp from 'path-to-regexp';

const VALID_METHODS = ['get', 'post', 'put', 'patch', 'delete'];

Expand Down Expand Up @@ -107,9 +108,13 @@ export default function getMockMiddleware(api) {
`mock value of ${key} should be function or object, but got ${type}`,
);
const { method, path } = parseKey(key);
const keys = [];
const re = pathToRegexp(path, keys);
memo.push({
method,
path,
re,
keys,
handler: createHandler(method, path, handler),
});
return memo;
Expand All @@ -128,13 +133,53 @@ export default function getMockMiddleware(api) {
const { path: exceptPath } = req;
const exceptMethod = req.method.toLowerCase();

return mockData.filter(({ method, path }) => {
return method === exceptMethod && path === exceptPath;
for (const mock of mockData) {
const { method, re, keys } = mock;
if (method === exceptMethod) {
const match = re.exec(req.path);
if (match) {
const params = {};

for (let i = 1; i < match.length; i = i + 1) {
const key = keys[i - 1];
const prop = key.name;
const val = decodeParam(match[i]);

if (val !== undefined || !hasOwnProperty.call(params, prop)) {
params[prop] = val;
}
}
req.params = params;
return mock;
}
}
}

function decodeParam(val) {
if (typeof val !== 'string' || val.length === 0) {
return val;
}

try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = `Failed to decode param ' ${val} '`;
err.status = err.statusCode = 400;
}

throw err;
}
}

return mockData.filter(({ method, re }) => {
return method === exceptMethod && re.test(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);
Expand Down

0 comments on commit 329e5bc

Please sign in to comment.