Skip to content

Commit

Permalink
Upgrade msw (#1580)
Browse files Browse the repository at this point in the history
  • Loading branch information
Methuselah96 authored Dec 19, 2023
1 parent 00664dc commit fa7af18
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 212 deletions.
4 changes: 2 additions & 2 deletions packages/redux-devtools-rtk-query-monitor/demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mswjs/data": "^0.15.0",
"@mswjs/data": "^0.16.1",
"@redux-devtools/core": "^4.0.0",
"@redux-devtools/dock-monitor": "^4.0.0",
"@redux-devtools/rtk-query-monitor": "^5.0.0",
"@reduxjs/toolkit": "^1.9.7",
"framer-motion": "^10.16.16",
"msw": "^1.3.2",
"msw": "^2.0.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.12.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
/* tslint:disable */

/**
* Mock Service Worker (1.3.2).
* Mock Service Worker (2.0.11).
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/

const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
const INTEGRITY_CHECKSUM = 'c5f7f8e188b673ea4e677df7ea3c5a39'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()

self.addEventListener('install', function () {
Expand Down Expand Up @@ -86,12 +87,6 @@ self.addEventListener('message', async function (event) {

self.addEventListener('fetch', function (event) {
const { request } = event
const accept = request.headers.get('accept') || ''

// Bypass server-sent events.
if (accept.includes('text/event-stream')) {
return
}

// Bypass navigation requests.
if (request.mode === 'navigate') {
Expand All @@ -112,29 +107,8 @@ self.addEventListener('fetch', function (event) {
}

// Generate unique request ID.
const requestId = Math.random().toString(16).slice(2)

event.respondWith(
handleRequest(event, requestId).catch((error) => {
if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
request.url,
)
return
}

// At this point, any exception indicates an issue with the original request/response.
console.error(
`\
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
`${error.name}: ${error.message}`,
)
}),
)
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId))
})

async function handleRequest(event, requestId) {
Expand All @@ -146,21 +120,24 @@ async function handleRequest(event, requestId) {
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const clonedResponse = response.clone()
sendToClient(client, {
type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
ok: clonedResponse.ok,
status: clonedResponse.status,
statusText: clonedResponse.statusText,
body:
clonedResponse.body === null ? null : await clonedResponse.text(),
headers: Object.fromEntries(clonedResponse.headers.entries()),
redirected: clonedResponse.redirected,
const responseClone = response.clone()

sendToClient(
client,
{
type: 'RESPONSE',
payload: {
requestId,
isMockedResponse: IS_MOCKED_RESPONSE in response,
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
body: responseClone.body,
headers: Object.fromEntries(responseClone.headers.entries()),
},
},
})
[responseClone.body],
)
})()
}

Expand Down Expand Up @@ -196,20 +173,20 @@ async function resolveMainClient(event) {

async function getResponse(event, client, requestId) {
const { request } = event
const clonedRequest = request.clone()

// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = request.clone()

function passthrough() {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const headers = Object.fromEntries(clonedRequest.headers.entries())
const headers = Object.fromEntries(requestClone.headers.entries())

// Remove MSW-specific request headers so the bypassed requests
// comply with the server's CORS preflight check.
// Operate with the headers as an object because request "Headers"
// are immutable.
delete headers['x-msw-bypass']
// Remove internal MSW request header so the passthrough request
// complies with any potential CORS preflight checks on the server.
// Some servers forbid unknown request headers.
delete headers['x-msw-intention']

return fetch(clonedRequest, { headers })
return fetch(requestClone, { headers })
}

// Bypass mocking when the client is not active.
Expand All @@ -227,31 +204,36 @@ async function getResponse(event, client, requestId) {

// Bypass requests with the explicit bypass header.
// Such requests can be issued by "ctx.fetch()".
if (request.headers.get('x-msw-bypass') === 'true') {
const mswIntention = request.headers.get('x-msw-intention')
if (['bypass', 'passthrough'].includes(mswIntention)) {
return passthrough()
}

// Notify the client that a request has been intercepted.
const clientMessage = await sendToClient(client, {
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
mode: request.mode,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.text(),
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
const requestBuffer = await request.arrayBuffer()
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: requestBuffer,
keepalive: request.keepalive,
},
},
})
[requestBuffer],
)

switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
Expand All @@ -261,21 +243,12 @@ async function getResponse(event, client, requestId) {
case 'MOCK_NOT_FOUND': {
return passthrough()
}

case 'NETWORK_ERROR': {
const { name, message } = clientMessage.data
const networkError = new Error(message)
networkError.name = name

// Rejecting a "respondWith" promise emulates a network error.
throw networkError
}
}

return passthrough()
}

function sendToClient(client, message) {
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()

Expand All @@ -287,17 +260,28 @@ function sendToClient(client, message) {
resolve(event.data)
}

client.postMessage(message, [channel.port2])
client.postMessage(
message,
[channel.port2].concat(transferrables.filter(Boolean)),
)
})
}

function sleep(timeMs) {
return new Promise((resolve) => {
setTimeout(resolve, timeMs)
async function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}

const mockedResponse = new Response(response.body, response)

Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
}

async function respondWithMock(response) {
await sleep(response.delay)
return new Response(response.body, response)
return mockedResponse
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { setupWorker } from 'msw';
import { setupWorker } from 'msw/browser';
import { handlers } from './db';

export const worker = setupWorker(...handlers);
38 changes: 20 additions & 18 deletions packages/redux-devtools-rtk-query-monitor/demo/src/mocks/db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { factory, primaryKey } from '@mswjs/data';
import { nanoid } from '@reduxjs/toolkit';
import { rest } from 'msw';
import { http, HttpResponse, delay } from 'msw';
import { Post } from '../services/posts';

const db = factory({
Expand All @@ -19,16 +19,16 @@ const db = factory({
});

export const handlers = [
rest.post<Post, never, Post | { error: string }>(
http.post<never, Post, Post | { error: string }>(
'/posts',
async (req, res, ctx) => {
const { name } = req.body;
async ({ request }) => {
const { name } = await request.json();

if (Math.random() < 0.3) {
return res(
ctx.json({ error: 'Oh no, there was an error, try again.' }),
ctx.status(500),
ctx.delay(300),
await delay(300);
return HttpResponse.json(
{ error: 'Oh no, there was an error, try again.' },
{ status: 500 },
);
}

Expand All @@ -37,28 +37,30 @@ export const handlers = [
name,
});

return res(ctx.json(post), ctx.delay(300));
await delay(300);
return HttpResponse.json(post);
},
),
rest.put<Post, { id: string }, Post | { error: string }>(
http.put<{ id: string }, Post, Post | { error: string }>(
'/posts/:id',
(req, res, ctx) => {
const { name } = req.body;
async ({ params, request }) => {
const { name } = await request.json();

if (Math.random() < 0.3) {
return res(
ctx.json({ error: 'Oh no, there was an error, try again.' }),
ctx.status(500),
ctx.delay(300),
await delay(300);
return HttpResponse.json(
{ error: 'Oh no, there was an error, try again.' },
{ status: 500 },
);
}

const post = db.post.update({
where: { id: { equals: req.params.id } },
where: { id: { equals: params.id } },
data: { name },
});

return res(ctx.json(post!), ctx.delay(300));
await delay(300);
return HttpResponse.json(post);
},
),
...db.post.toHandlers('rest'),
Expand Down
Loading

0 comments on commit fa7af18

Please sign in to comment.