Allow option to change JSON parser behaviour #1224
Unanswered
anthonyma94
asked this question in
Q&A
Replies: 1 comment 3 replies
-
Hey, @anthonyma94. Thanks for suggesting this. You can achieve custom JSON parsing using the current MSW API. I think the most straightforward option is to write a higher-order resolver function that'd encapsulate the JSON parsing logic. // Write a custom response resolver that'd properly parse "hal+json"
// request bodies.
function withHalJson(resolver) {
return (req, res, ctx) => {
// You probably want to account for non-JSON request bodies.
if (req.headers.get('content-type')?.includes('hal+json')) {
// Get the original request body and provide additional parsing.
// Keep in mind that MSW will attempt to parse "application/json"
// request bodies automatically. You may be operating on a parsed result here.
const json = req.body
const halJson = parseInSomeWay(json)
// Replace the original body.
req.body = halJson
}
return resolver(req, res, ctx)
}
}
rest.post('/resource', withHalJson((req, res, ctx) => {
req.body // It's custom parsed request body now.
})) Let me know if this would work for your use case. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Scope
Adds a new behavior
Compatibility
Feature description
In Express, there is an option to change the behavior of the JSON parser:
This option is also built-in to JSON.parse:
It would be great if MSW could implement something like this globally for
req.body
, it would make mocking a backend a lot closer to production.Beta Was this translation helpful? Give feedback.
All reactions