Skip to content

Commit

Permalink
fix(mock): exact match priority, close #508
Browse files Browse the repository at this point in the history
  • Loading branch information
cipchk committed Jun 15, 2018
1 parent 1c0be3e commit 4fb004a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
10 changes: 8 additions & 2 deletions packages/mock/src/mock.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,14 @@ describe('mock: service', () => {
const editRes = editRule.callback(editRule as any);
expect(editRes.s).toBe('edit');
const detailRule = srv.getRule('GET', '/users/1');
const detailRes = detailRule.callback(detailRule as any);
expect(detailRes.s).toBe('detail');
expect((detailRule.callback as any).rank).not.toBeUndefined();
});

it('should be exact match priority', () => {
const detail1Rule = srv.getRule('GET', '/users/1');
expect((detail1Rule.callback as any).rank).not.toBeUndefined();
const detail2Rule = srv.getRule('GET', '/users/2');
expect(detail2Rule.callback.name).toBe('/users/:id');
});
});

Expand Down
12 changes: 7 additions & 5 deletions packages/mock/src/mock.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ export class MockService implements OnDestroy {
typeof value === 'object' ||
typeof value === 'string'
)
)
) {
throw Error(
`mock value of [${key}-${ruleKey}] should be function or object or string, but got ${typeof value}`,
);
}
const rule = this.genRule(ruleKey, value);
if (
['GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'PATCH', 'OPTIONS'].indexOf(
Expand Down Expand Up @@ -122,13 +123,14 @@ export class MockService implements OnDestroy {
getRule(method: string, url: string): MockRule {
method = (method || 'GET').toUpperCase();
const params: any = {};
const ret =
this.cached.find(
const list =
this.cached.filter(
w =>
w.method === method &&
(w.martcher ? w.martcher.test(url) : w.url === url),
) || null;
if (!ret) return null;
);
if (list.length === 0) return null;
const ret = list.find(w => w.url === url) || list[0];
if (ret.martcher) {
const execArr = ret.martcher.exec(url);
execArr.slice(1).map((value: string, index: number) => {
Expand Down

0 comments on commit 4fb004a

Please sign in to comment.