Skip to content

Commit

Permalink
Add withDelay middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
djhi committed Jun 4, 2024
1 parent b1a0a00 commit 5570922
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
7 changes: 4 additions & 3 deletions example/msw.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { setupWorker } from 'msw/browser';
import { MswServer } from '../src/FakeRest';
import { MswServer, withDelay } from '../src/FakeRest';
import { data } from './data';
import { HttpResponse } from 'msw';

Expand All @@ -8,17 +8,18 @@ const restServer = new MswServer({
data,
});

restServer.addMiddleware(withDelay(5000));
restServer.addMiddleware(async (request, context, next) => {
if (!request.headers?.get('Authorization')) {
return new HttpResponse(null, { status: 401 });
throw new HttpResponse(null, { status: 401 });
}

if (
context.collection === 'books' &&
request.method === 'POST' &&
!context.requestJson?.title
) {
return new HttpResponse(null, {
throw new HttpResponse(null, {
status: 400,
statusText: 'Title is required',
});
Expand Down
3 changes: 3 additions & 0 deletions src/FakeRest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { Collection } from './Collection.js';
import { Single } from './Single.js';
import { getMswHandlers, MswServer } from './msw.js';
import { withDelay } from './withDelay.js';

export {
getSinonHandler,
Expand All @@ -19,6 +20,7 @@ export {
MswServer,
Collection,
Single,
withDelay,
};

export default {
Expand All @@ -32,4 +34,5 @@ export default {
MswServer,
Collection,
Single,
withDelay,
};
11 changes: 11 additions & 0 deletions src/withDelay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Middleware } from './BaseServerWithMiddlewares.js';

export const withDelay =
<RequestType>(delayMs: number): Middleware<RequestType> =>
(request, context, next) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(next(request, context));
}, delayMs);
});
};

0 comments on commit 5570922

Please sign in to comment.