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

feat(msw): allow mock delay override via function #945

Merged
merged 2 commits into from
Sep 28, 2023
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
4 changes: 2 additions & 2 deletions docs/src/pages/reference/configuration/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,9 +745,9 @@ module.exports = {

##### delay

Type: `number`.
Type: `number` or `Function`.

Give you the possibility to set delay time for mock
Give you the possibility to set delay time for mock. It can either be a fixed number or a function that returns a number.

Default Value: `1000`

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export type NormalizedOverrideOutput = {
format?: { [key: string]: unknown };
required?: boolean;
baseUrl?: string;
delay?: number;
delay?: number | (() => number);
};
contentType?: OverrideOutputContentType;
header: false | ((info: InfoObject) => string[] | string);
Expand Down
15 changes: 14 additions & 1 deletion packages/msw/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
GeneratorDependency,
GeneratorOptions,
GeneratorVerbOptions,
NormalizedOverrideOutput,
pascal,
} from '@orval/core';
import { getRouteMSW } from './getters';
Expand Down Expand Up @@ -36,6 +37,18 @@ export const generateMSWImports: GenerateMockImports = ({
);
};

const getDelay = (override?: NormalizedOverrideOutput): number => {
const overrideDelay = override?.mock?.delay;
switch (typeof overrideDelay) {
case 'function':
return overrideDelay();
case 'number':
return overrideDelay;
default:
return 1000;
}
};

export const generateMSW = (
{ operationId, response, verb, tags }: GeneratorVerbOptions,
{ pathRoute, override, context }: GeneratorOptions,
Expand Down Expand Up @@ -73,7 +86,7 @@ export const generateMSW = (
: '',
handler: `rest.${verb}('${route}', (_req, res, ctx) => {
return res(
ctx.delay(${override?.mock?.delay ?? 1000}),
ctx.delay(${getDelay(override)}),
ctx.status(200, 'Mocked status'),${
value && value !== 'undefined'
? `\nctx.${responseType}(get${pascal(operationId)}Mock()),`
Expand Down