Skip to content

Commit ca4fb6f

Browse files
committed
feat: Add regex support to match in response actions
1 parent 2776f77 commit ca4fb6f

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed

src/runtime/helpers.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,26 @@ export function matchRequest(
3737
return true;
3838
}
3939

40+
// eslint-disable-next-line complexity
4041
export function matchResponse(
4142
verb: string,
42-
path: string,
43+
path: string | RegExp,
4344
response: AxiosResponse,
4445
params?: object,
4546
) {
46-
return (
47-
response.config.method === verb &&
48-
response.config.url === path &&
49-
hasSameParams(response.config.params, params)
50-
);
47+
const { config } = response;
48+
if (!config.url) return false;
49+
const samePath = matchPaths(path, config.url);
50+
const requestURL = new $URL(config.url);
51+
52+
const sameMethod = config.method === verb;
53+
54+
if (!sameMethod) return false;
55+
if (!samePath) return false;
56+
57+
if (params) return hasSameParams(params, config.params || requestURL.query);
58+
59+
return true;
5160
}
5261

5362
export function ejectFromRequest(axios: AxiosInstance, id: number) {

test/index.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,25 @@ describe('axios-dev-proxy tests', () => {
356356
expect(consoleLog).toBeCalledTimes(2);
357357
});
358358

359+
it('should print response once with regex on match', async () => {
360+
server
361+
.get('/print-response')
362+
.reply(200, { data: 1 })
363+
.get('/print-response')
364+
.reply(200, { data: 2 });
365+
const consoleLog = vi.spyOn(console, 'log');
366+
proxy.onGet(/\/print-\w+/).printResponseOnce();
367+
368+
await api.get('/print-response');
369+
await api.get('/print-response');
370+
371+
expect(consoleLog).toHaveBeenNthCalledWith(
372+
2,
373+
JSON.stringify({ data: 1 }, null, 2),
374+
);
375+
expect(consoleLog).toBeCalledTimes(2);
376+
});
377+
359378
it('should change the request config', async () => {
360379
const server2 = nock('https://api-2.com.br');
361380
server2.get('/config').reply(200, { data: 2 });

0 commit comments

Comments
 (0)