request
Request (req) is an object that stores the information about a matched request.
Unlike a NodeJS Request, the request object in Mock Service Worker is a partial request representation. This is due to the limitations on the nature of the data that can be transferred between a Service Worker and a client processes.
The
req object of the same response resolve will be different in browser and Node environment. Certain request properties are not available in Node (i.e. credentials, integrity or destination). The values of such properties are set to sensible defaults when referenced in Node environment.Properties
| Property | Type |
|---|---|
url | URL |
body | string, Record<string, any> |
method | Request.method |
headers | Request.headers |
cookies | Record<string, string> |
params | Record<string, string> |
bodyUsed | Request.bodyUsed |
cache | Request.cache |
mode | Request.mode |
credentials | Request.credentials |
redirect | Request.redirect |
referrer | Request.referrer |
referrerPolicy | Request.referrerPolicy |
integrity | Request.integrity |
destination | Request.destination |
keepalive | boolean |
GraphQL
When mocking a GraphQL API, the req object contains the following extra properties:
| Property | Type |
|---|---|
variables | Record<string, string> |
Examples
Path parameter
1rest.post('/user/:userId/articles', (req, res, ctx) => {2 const { userId } = req.params3 return res(ctx.text(userId))4})
GraphQL variable
1graphql.mutation('Login', (req, res, ctx) => {2 const { username } = req.variables34 return res(5 ctx.data({6 user: { name: 'John ' },7 }),8 )9})