Skip to content

Commit 2c54132

Browse files
authored
fix: fixing some stuffs for integrations with api (#26)
1 parent fd25549 commit 2c54132

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

64 files changed

+904
-673
lines changed

public/mockServiceWorker.js

Lines changed: 83 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
/* tslint:disable */
33

44
/**
5-
* Mock Service Worker (0.47.4).
5+
* Mock Service Worker.
66
* @see https://github.com/mswjs/msw
77
* - Please do NOT modify this file.
88
* - Please do NOT serve this file on production.
99
*/
1010

11-
const INTEGRITY_CHECKSUM = 'b3066ef78c2f9090b4ce87e874965995'
11+
const PACKAGE_VERSION = '2.4.5'
12+
const INTEGRITY_CHECKSUM = '26357c79639bfa20d64c0efca2a87423'
13+
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
1214
const activeClientIds = new Set()
1315

1416
self.addEventListener('install', function () {
@@ -47,7 +49,10 @@ self.addEventListener('message', async function (event) {
4749
case 'INTEGRITY_CHECK_REQUEST': {
4850
sendToClient(client, {
4951
type: 'INTEGRITY_CHECK_RESPONSE',
50-
payload: INTEGRITY_CHECKSUM,
52+
payload: {
53+
packageVersion: PACKAGE_VERSION,
54+
checksum: INTEGRITY_CHECKSUM,
55+
},
5156
})
5257
break
5358
}
@@ -86,12 +91,6 @@ self.addEventListener('message', async function (event) {
8691

8792
self.addEventListener('fetch', function (event) {
8893
const { request } = event
89-
const accept = request.headers.get('accept') || ''
90-
91-
// Bypass server-sent events.
92-
if (accept.includes('text/event-stream')) {
93-
return
94-
}
9594

9695
// Bypass navigation requests.
9796
if (request.mode === 'navigate') {
@@ -100,10 +99,7 @@ self.addEventListener('fetch', function (event) {
10099

101100
// Opening the DevTools triggers the "only-if-cached" request
102101
// that cannot be handled by the worker. Bypass such requests.
103-
if (
104-
request.cache === 'only-if-cached' &&
105-
request.mode !== 'same-origin'
106-
) {
102+
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
107103
return
108104
}
109105

@@ -115,29 +111,8 @@ self.addEventListener('fetch', function (event) {
115111
}
116112

117113
// Generate unique request ID.
118-
const requestId = Math.random().toString(16).slice(2)
119-
120-
event.respondWith(
121-
handleRequest(event, requestId).catch((error) => {
122-
if (error.name === 'NetworkError') {
123-
console.warn(
124-
'[MSW] Successfully emulated a network error for the "%s %s" request.',
125-
request.method,
126-
request.url,
127-
)
128-
return
129-
}
130-
131-
// At this point, any exception indicates an issue with the original request/response.
132-
console.error(
133-
`\
134-
[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.`,
135-
request.method,
136-
request.url,
137-
`${error.name}: ${error.message}`,
138-
)
139-
}),
140-
)
114+
const requestId = crypto.randomUUID()
115+
event.respondWith(handleRequest(event, requestId))
141116
})
142117

143118
async function handleRequest(event, requestId) {
@@ -149,23 +124,24 @@ async function handleRequest(event, requestId) {
149124
// this message will pend indefinitely.
150125
if (client && activeClientIds.has(client.id)) {
151126
;(async function () {
152-
const clonedResponse = response.clone()
153-
sendToClient(client, {
154-
type: 'RESPONSE',
155-
payload: {
156-
requestId,
157-
type: clonedResponse.type,
158-
ok: clonedResponse.ok,
159-
status: clonedResponse.status,
160-
statusText: clonedResponse.statusText,
161-
body:
162-
clonedResponse.body === null
163-
? null
164-
: await clonedResponse.text(),
165-
headers: Object.fromEntries(clonedResponse.headers.entries()),
166-
redirected: clonedResponse.redirected,
127+
const responseClone = response.clone()
128+
129+
sendToClient(
130+
client,
131+
{
132+
type: 'RESPONSE',
133+
payload: {
134+
requestId,
135+
isMockedResponse: IS_MOCKED_RESPONSE in response,
136+
type: responseClone.type,
137+
status: responseClone.status,
138+
statusText: responseClone.statusText,
139+
body: responseClone.body,
140+
headers: Object.fromEntries(responseClone.headers.entries()),
141+
},
167142
},
168-
})
143+
[responseClone.body],
144+
)
169145
})()
170146
}
171147

@@ -179,7 +155,7 @@ async function handleRequest(event, requestId) {
179155
async function resolveMainClient(event) {
180156
const client = await self.clients.get(event.clientId)
181157

182-
if (client.frameType === 'top-level') {
158+
if (client?.frameType === 'top-level') {
183159
return client
184160
}
185161

@@ -201,20 +177,20 @@ async function resolveMainClient(event) {
201177

202178
async function getResponse(event, client, requestId) {
203179
const { request } = event
204-
const clonedRequest = request.clone()
180+
181+
// Clone the request because it might've been already used
182+
// (i.e. its body has been read and sent to the client).
183+
const requestClone = request.clone()
205184

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

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

217-
return fetch(clonedRequest, { headers })
193+
return fetch(requestClone, { headers })
218194
}
219195

220196
// Bypass mocking when the client is not active.
@@ -230,57 +206,46 @@ async function getResponse(event, client, requestId) {
230206
return passthrough()
231207
}
232208

233-
// Bypass requests with the explicit bypass header.
234-
// Such requests can be issued by "ctx.fetch()".
235-
if (request.headers.get('x-msw-bypass') === 'true') {
236-
return passthrough()
237-
}
238-
239209
// Notify the client that a request has been intercepted.
240-
const clientMessage = await sendToClient(client, {
241-
type: 'REQUEST',
242-
payload: {
243-
id: requestId,
244-
url: request.url,
245-
method: request.method,
246-
headers: Object.fromEntries(request.headers.entries()),
247-
cache: request.cache,
248-
mode: request.mode,
249-
credentials: request.credentials,
250-
destination: request.destination,
251-
integrity: request.integrity,
252-
redirect: request.redirect,
253-
referrer: request.referrer,
254-
referrerPolicy: request.referrerPolicy,
255-
body: await request.text(),
256-
bodyUsed: request.bodyUsed,
257-
keepalive: request.keepalive,
210+
const requestBuffer = await request.arrayBuffer()
211+
const clientMessage = await sendToClient(
212+
client,
213+
{
214+
type: 'REQUEST',
215+
payload: {
216+
id: requestId,
217+
url: request.url,
218+
mode: request.mode,
219+
method: request.method,
220+
headers: Object.fromEntries(request.headers.entries()),
221+
cache: request.cache,
222+
credentials: request.credentials,
223+
destination: request.destination,
224+
integrity: request.integrity,
225+
redirect: request.redirect,
226+
referrer: request.referrer,
227+
referrerPolicy: request.referrerPolicy,
228+
body: requestBuffer,
229+
keepalive: request.keepalive,
230+
},
258231
},
259-
})
232+
[requestBuffer],
233+
)
260234

261235
switch (clientMessage.type) {
262236
case 'MOCK_RESPONSE': {
263237
return respondWithMock(clientMessage.data)
264238
}
265239

266-
case 'MOCK_NOT_FOUND': {
240+
case 'PASSTHROUGH': {
267241
return passthrough()
268242
}
269-
270-
case 'NETWORK_ERROR': {
271-
const { name, message } = clientMessage.data
272-
const networkError = new Error(message)
273-
networkError.name = name
274-
275-
// Rejecting a "respondWith" promise emulates a network error.
276-
throw networkError
277-
}
278243
}
279244

280245
return passthrough()
281246
}
282247

283-
function sendToClient(client, message) {
248+
function sendToClient(client, message, transferrables = []) {
284249
return new Promise((resolve, reject) => {
285250
const channel = new MessageChannel()
286251

@@ -292,17 +257,28 @@ function sendToClient(client, message) {
292257
resolve(event.data)
293258
}
294259

295-
client.postMessage(message, [channel.port2])
260+
client.postMessage(
261+
message,
262+
[channel.port2].concat(transferrables.filter(Boolean)),
263+
)
296264
})
297265
}
298266

299-
function sleep(timeMs) {
300-
return new Promise((resolve) => {
301-
setTimeout(resolve, timeMs)
267+
async function respondWithMock(response) {
268+
// Setting response status code to 0 is a no-op.
269+
// However, when responding with a "Response.error()", the produced Response
270+
// instance will have status code set to 0. Since it's not possible to create
271+
// a Response instance with status code 0, handle that use-case separately.
272+
if (response.status === 0) {
273+
return Response.error()
274+
}
275+
276+
const mockedResponse = new Response(response.body, response)
277+
278+
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
279+
value: true,
280+
enumerable: true,
302281
})
303-
}
304282

305-
async function respondWithMock(response) {
306-
await sleep(response.delay)
307-
return new Response(response.body, response)
283+
return mockedResponse
308284
}

src/components/Comments/Comments.tsx

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -221,21 +221,23 @@ function Comments(props: CommentsProps) {
221221
</IconButton>
222222
</Tooltip>
223223

224-
<ActionDialog
225-
title="Remove comment"
226-
description="This action is irreversible. Are you sure?"
227-
confirmAction={() => handleDelete(comment.id)}
228-
trigger={
229-
<Tooltip title="Remove comment">
230-
<IconButton>
231-
<Icon
232-
name="IoTrashOutline"
233-
className="text-theme-red-900"
234-
/>
235-
</IconButton>
236-
</Tooltip>
237-
}
238-
/>
224+
{comment.by.id === user?.id && (
225+
<ActionDialog
226+
title="Remove comment"
227+
description="This action is irreversible. Are you sure?"
228+
confirmAction={() => handleDelete(comment.id)}
229+
trigger={
230+
<Tooltip title="Remove comment">
231+
<IconButton>
232+
<Icon
233+
name="IoTrashOutline"
234+
className="text-theme-red-900"
235+
/>
236+
</IconButton>
237+
</Tooltip>
238+
}
239+
/>
240+
)}
239241

240242
<Box className="flex items-center gap-2">
241243
{comment.by.id === user?.id ? (
@@ -301,7 +303,7 @@ function Comments(props: CommentsProps) {
301303
</Avatar>
302304
<ListItemText
303305
primary={reply.comment}
304-
secondary={`by ${reply.by.nickname}, ${formatRelative(new Date(reply.created_at), new Date())}`}
306+
secondary={`by ${reply.by.nickname === user?.nickname ? 'me' : reply.by.nickname}, ${formatRelative(new Date(reply.created_at), new Date())}`}
305307
primaryTypographyProps={{
306308
className:
307309
'dark:text-gray-400 text-gray-600 break-words',
@@ -321,7 +323,26 @@ function Comments(props: CommentsProps) {
321323
<Icon name="IoChatboxEllipsesOutline" />
322324
</IconButton>
323325
</Tooltip>
324-
{reply.by.id !== user?.id && (
326+
{reply.by.id === user?.id && (
327+
<ActionDialog
328+
title="Remove reply"
329+
description="This action is irreversible. Are you sure?"
330+
confirmAction={() => handleDelete(reply.id)}
331+
trigger={
332+
<Tooltip title="Remove reply">
333+
<IconButton>
334+
<Icon
335+
name="IoTrashOutline"
336+
className="text-theme-red-900"
337+
/>
338+
</IconButton>
339+
</Tooltip>
340+
}
341+
/>
342+
)}
343+
{reply.by.id === user?.id ? (
344+
<Icon name="IoHeartOutline" size={28} />
345+
) : (
325346
<HeartButton
326347
heartable_id={reply.id}
327348
heartable_type="commentables"
@@ -341,7 +362,7 @@ function Comments(props: CommentsProps) {
341362
)}
342363
<Typography
343364
variant="body2"
344-
className="dark:text-white text-gray-800">
365+
className="dark:text-white text-gray-800 ml-2">
345366
{reply.hearts_count}
346367
</Typography>
347368
</Box>

0 commit comments

Comments
 (0)