mswjs / http-middleware

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.

Home Page:https://npm.im/@mswjs/http-middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Update handlers

fvanwijk opened this issue · comments

In msw you can do setupServer(...handlers) / setupWorker(...handlers) but also worker.use(...handler) to override existing handlers.

This package runs middleware in express and it looks like when you set the handlers with setupServer(...handlers), it is not possible to override them using something like server.use. Is that correct?

I have created an extension on top of @mswjs/http-middleware to set/change handlers on run time by calling a special PUT endpoint. It replaces the resolvers for the registered handlers, but the solution would be cleaner when it replaces the complete endpoints with a similar API as worker.use.

You can find the repo at fvanwijk/msw-http-dynamic-middleware.

Hey, @fvanwijk.

This middleware is not an abstraction over the familiar setupWorker/setupServer API. You can imagine this middleware being an alternative API to the said functions. It resolves an incoming request against the list of handlers directly and doesn't keep any sort of internal state (like worker/server does) to manage runtime handlers.

await handleRequest(
mockedRequest,
handlers,

Keeping such a state is not how middleware works, to my best knowledge. I've never seen an API like this in practice:

const api = middleware(initialOptions)
app.use(api)
// And expect that the changes will be applied to the "app".
api.modify(...)

That would be a confusing API to use, in my opinion, as anything can modify the middleware from anywhere, producing a code you cannot predict.

Given that this package is primarily designed for observational purposes, I see little value in considering the runtime handlers' support. The use case you describe may be valid in the context of your extension and you can manage such state internally instead. I can suggest creating a higher-order function over the createMiddleware that encapsulates the handlers state, similar to how it's written in MSW.

The dependency cost of introducing this abstraction is low, as the request handler API is stable at this point and you can store the handlers in whichever data structure you see fit. You'd have to re-instantiate the middleware for the changes to take effect, bringing you to the right surface to address this feature (the ability to re-instantiate a middleware).