From 5570922df2f283688822c7d8732e8c238ff9c446 Mon Sep 17 00:00:00 2001 From: Gildas Garcia <1122076+djhi@users.noreply.github.com> Date: Tue, 4 Jun 2024 09:48:38 +0200 Subject: [PATCH] Add withDelay middleware --- example/msw.ts | 7 ++++--- src/FakeRest.ts | 3 +++ src/withDelay.ts | 11 +++++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 src/withDelay.ts diff --git a/example/msw.ts b/example/msw.ts index 1b75528..ce8d0b8 100644 --- a/example/msw.ts +++ b/example/msw.ts @@ -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'; @@ -8,9 +8,10 @@ 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 ( @@ -18,7 +19,7 @@ restServer.addMiddleware(async (request, context, next) => { request.method === 'POST' && !context.requestJson?.title ) { - return new HttpResponse(null, { + throw new HttpResponse(null, { status: 400, statusText: 'Title is required', }); diff --git a/src/FakeRest.ts b/src/FakeRest.ts index 281e3c7..994ba6d 100644 --- a/src/FakeRest.ts +++ b/src/FakeRest.ts @@ -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, @@ -19,6 +20,7 @@ export { MswServer, Collection, Single, + withDelay, }; export default { @@ -32,4 +34,5 @@ export default { MswServer, Collection, Single, + withDelay, }; diff --git a/src/withDelay.ts b/src/withDelay.ts new file mode 100644 index 0000000..d538825 --- /dev/null +++ b/src/withDelay.ts @@ -0,0 +1,11 @@ +import type { Middleware } from './BaseServerWithMiddlewares.js'; + +export const withDelay = + (delayMs: number): Middleware => + (request, context, next) => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(next(request, context)); + }, delayMs); + }); + };