Skip to content

Commit

Permalink
Merge pull request #119 from traPtitech/feat/msw_update
Browse files Browse the repository at this point in the history
mswをv2にした
  • Loading branch information
mehm8128 authored Jan 8, 2024
2 parents 6a30b74 + 433db1a commit affea3c
Show file tree
Hide file tree
Showing 13 changed files with 437 additions and 544 deletions.
493 changes: 189 additions & 304 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"eslint-plugin-vue": "^9.17.0",
"esno": "^0.17.0",
"execa": "^8.0.1",
"msw": "^1.3.2",
"msw": "^2.0.5",
"prettier": "^3.0.3",
"prettier-plugin-tailwindcss": "^0.5.5",
"rollup-plugin-brotli": "^3.1.0",
Expand Down
175 changes: 82 additions & 93 deletions public/mockServiceWorker.js
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.5).
* @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 = '0877fcdc026242810f5bfde0d7178db4'
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,29 @@ 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()
// When performing original requests, response body will
// always be a ReadableStream, even for 204 responses.
// But when creating a new Response instance on the client,
// the body for a 204 response must be null.
const responseBody = response.status === 204 ? null : responseClone.body

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

Expand Down Expand Up @@ -196,20 +178,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 +209,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 +248,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 +265,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
}
16 changes: 15 additions & 1 deletion src/App.vue
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
<script lang="ts" setup>
import { onMounted } from 'vue'
import { onMounted , watch } from 'vue'
import { useFetchMeUsecase } from '/@/features/user/usecase'
import JomonHeader from './components/navigation/JomonHeader.vue'
import './styles/main.css'
import './styles/toast.css'
import { useRoute } from 'vue-router'
onMounted(async () => {
await useFetchMeUsecase()
})
const route = useRoute()
watch(
() => route.fullPath,
async () => {
try {
await useFetchMeUsecase()
} catch {
document.location = 'https://jomon-dev.trapti.tech/api/auth/genpkce'
}
}
)
</script>

<template>
Expand Down
21 changes: 12 additions & 9 deletions src/features/admin/mock.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { rest } from 'msw'
import { HttpResponse, type PathParams, http } from 'msw'

const mockAdmins = ['3fa85f64-5717-4562-b3fc-2c963f66afa6']

export const adminHandlers = [
rest.get('/api/admins', (req, res, ctx) => {
return res(ctx.status(200), ctx.json<string[]>(mockAdmins))
http.get('/api/admins', () => {
return HttpResponse.json(mockAdmins)
}),
rest.post('/api/admins', async (req, res, ctx) => {
const reqBody: string[] = await req.json()
return res(ctx.status(200), ctx.json<string[]>(reqBody))
}),
rest.delete('/api/admins', (req, res, ctx) => {
return res(ctx.status(200))
http.post<PathParams, string[], string[]>(
'/api/admins',
async ({ request }) => {
const reqBody: string[] = await request.json()
return HttpResponse.json(reqBody)
}
),
http.delete('/api/admins', () => {
return HttpResponse.json(null)
})
]
22 changes: 9 additions & 13 deletions src/features/file/mock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { rest } from 'msw'
import { HttpResponse, http } from 'msw'

import type { FileMeta } from '/@/lib/apis'

Expand All @@ -14,19 +14,15 @@ const mockFileMeta: FileMeta = {
}

export const fileHandlers = [
rest.get('/api/files/:id', (req, res, ctx) => {
return res(ctx.status(200), ctx.text(mockFile))
http.get('/api/files/:id', () => {
return HttpResponse.text(mockFile)
}),
rest.get('/api/files/:id/meta', (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json<FileMeta>({ ...mockFileMeta, id: req.params.id as string })
)
http.get('/api/files/:id/meta', ({ params }) => {
const res: FileMeta = { ...mockFileMeta, id: params.id as string }

return HttpResponse.json(res)
}),
rest.post('/api/files', (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({ id: '3fa85f64-5717-4562-b3fc-2c963f66afa6' })
)
http.post('/api/files', () => {
return HttpResponse.json({ id: '3fa85f64-5717-4562-b3fc-2c963f66afa6' })
})
]
Loading

0 comments on commit affea3c

Please sign in to comment.