Use @mswjs/interceptors for transparently cache responses #1546
-
Hello! I know this might not be the right place to ask, but I couldn't find an analogue use case among the all the issues so I thought could be useful. As mentioned in the title, I would like to know if it could be possible to use this library for transparently caching API calls. In my case, our project has a script loaded externally through the script tag which loads some WebComponents that automatically does data fetching, and that script uses Axios internally, whereas our API calls are made with Axios too. My idea was to use the interceptors to capture the requests and cache their response somewhere. My first attempt was to use another this https://github.com/arthurfiorette/axios-cache-interceptor library and try to route all the requests through this axios client which already implements caching, so that I wouldn't need to bother too much reinventing the wheel, just to discover an infinite loop, obviously. So I'm here to ask if there is already a library that does this automagically or maybe suggest me how to approach this problem. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey, @c3n21. That's a great question. What you describing should be possible to do with MSW. If you're in the browser, you can use the import { setupWorker, rest } from 'msw'
const worker = setupWorker(
rest.get('/third-party-call-url', (req, res, ctx) => {
// Lookup this request in some internal cache.
const response = someCache.get(req)
// Respond with a cached response, if found.
if (typeof response !== 'undefined') {
return res(
}
// If no cache hit, retrieve the original response
// and cache it.
const originalResponse = await ctx.fetch(req)
someCache.set(req, originalResponse)
// Here you can either passthrough, which would perform this
// request once again, or return a mocked response out of
// the "originalResponse" above.
return req.passthrough()
})
)
worker.start() You can use whichever you fancy for the internal cache implementation: simple One thing to keep in mind that Hope this helps. |
Beta Was this translation helpful? Give feedback.
Hey, @c3n21. That's a great question.
What you describing should be possible to do with MSW. If you're in the browser, you can use the
setupWorker()
API to intercept any outgoing requests, regardless if they are issued by your code or by a third-party that loads web components.