Skip to content

Commit

Permalink
refactor: route update after update query feature
Browse files Browse the repository at this point in the history
  • Loading branch information
minsgy committed Jun 9, 2024
1 parent 29c0f10 commit 6b12fbd
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 46 deletions.
7 changes: 6 additions & 1 deletion src/app/MSWDevtools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const MSWDevtools = ({
isEnabled = false,
children,
worker,
onRouteUpdate,
}: MSWDevtoolsProps) => {
if ((isEnabled && !worker) || (isEnabled && worker && !worker)) {
console.warn(
Expand All @@ -20,7 +21,11 @@ export const MSWDevtools = ({

return (
<>
<MswDevToolsProvider isEnabled={isEnabled} worker={worker}>
<MswDevToolsProvider
isEnabled={isEnabled}
worker={worker}
onRouteUpdate={onRouteUpdate}
>
<MSWDevtoolsPanel />
</MswDevToolsProvider>
{children}
Expand Down
2 changes: 1 addition & 1 deletion src/features/DevtoolsHandlerList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const DevtoolsHandlerList = () => {
{routes.map((route) => (
<li key={route.id} className="p-[12px] flex items-center">
<Switch
checked={route.isSkip}
checked={route.enabled}
onCheckedChange={(checked) => {
onToggleHandler(route.id, checked)
}}
Expand Down
26 changes: 19 additions & 7 deletions src/hooks/useMswDevtoolsState.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
"use client"

import { useState, useCallback, useEffect } from "react"
import { useState, useCallback, useEffect, useRef } from "react"
import { MswDevtoolsContextType } from "../providers/useMswDevtoolsContext"
import { EnhancedDevtoolsRoute } from ".."
import { generatorSerializedRouteHandlers } from "@/shared/utils/generatorSerializedRouteHandlers"
import { generatorRequestHandler } from "@/shared/utils/generatorRequestHandler"

export const useMswDevtoolsState = (initialState: MswDevtoolsContextType) => {
export const useMswDevtoolsState = ({
onRouteUpdate,
...initialState
}: MswDevtoolsContextType) => {
const isMounted = useRef(false)
const [state, setState] = useState(initialState)
const [routes, setRoutes] = useState<EnhancedDevtoolsRoute[]>(
generatorSerializedRouteHandlers(initialState.worker?.listHandlers() ?? [])
)

const setEnabled = useCallback((isEnabled: boolean) => {
setState((prev) => ({
...prev,
Expand All @@ -26,10 +31,10 @@ export const useMswDevtoolsState = (initialState: MswDevtoolsContextType) => {
setRoutes((prev) => [...prev, route])
}

const onToggleHandler = (id: string, isSkip: boolean) => {
const onToggleHandler = (id: string, enabled: boolean) => {
const findIndex = routes.findIndex((route) => route.id === id)
const newRoutes = [...routes]
newRoutes[findIndex].isSkip = isSkip
newRoutes[findIndex].enabled = enabled
setRoutes(newRoutes)
}

Expand All @@ -42,15 +47,22 @@ export const useMswDevtoolsState = (initialState: MswDevtoolsContextType) => {

useEffect(() => {
if (state.worker) {
const usedRoutes = routes.filter(({ isSkip }) => isSkip)
state.worker.resetHandlers(...generatorRequestHandler(usedRoutes))
const usedRoutes = routes.filter(({ enabled }) => enabled)
const httpUsedRoutes = generatorRequestHandler(usedRoutes)
state.worker.resetHandlers(...httpUsedRoutes)
// first call is not needed
if (isMounted.current) {
onRouteUpdate?.(usedRoutes.filter(({ isHidden }) => !isHidden))
} else {
isMounted.current = true
}
}
}, [routes, state.worker])

return {
state,
setEnabled,
routes,
routes: routes.filter(({ isHidden }) => !isHidden),
setRoutes,
onDeleteHandler,
onAddHandler,
Expand Down
10 changes: 5 additions & 5 deletions src/providers/useMswDevtoolsContext.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"use client"

import constate from "constate"
import { SetupWorker } from "msw/lib/browser"
import { useMswDevtoolsState } from "../hooks/useMswDevtoolsState"
import { useEditorPanelState } from "@/hooks/useEditorPanelState"
import { MSWDevtoolsProps } from ".."

export type MswDevtoolsContextType = {
isEnabled: boolean
worker?: SetupWorker
}
export type MswDevtoolsContextType = Omit<
MSWDevtoolsProps,
"children" | "position"
>

const [
MswDevToolsProvider,
Expand Down
1 change: 1 addition & 0 deletions src/shared/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./http"
14 changes: 10 additions & 4 deletions src/shared/utils/createHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DevtoolsRoute } from "@/types"
import { EnhancedDevtoolsRoute } from "@/types"
import { faker } from "@faker-js/faker"
import {
HttpHandler,
Expand All @@ -9,16 +9,22 @@ import {
delay,
} from "msw"

export const createHandler = (route: DevtoolsRoute): RequestHandler | null => {
const { method, url, handlers, selectedHandlerId } = route
export const createHandler = (
route: EnhancedDevtoolsRoute
): RequestHandler | null => {
const { method, url, handlers, selectedHandlerId, isHidden } = route

const httpHandler = createHttpHandler(method)
return httpHandler(url, async (info) => {
const selectedHandler =
handlers.find((handler) => handler.id === selectedHandlerId) ??
handlers[0]
const jsonResponse = JSON.parse(selectedHandler.response)

if (isHidden) {
return new HttpResponse()
}

const jsonResponse = JSON.parse(selectedHandler.response)
if (jsonResponse) {
recursiveTransform(jsonResponse, (key, value) => {
if (typeof value === "number") {
Expand Down
78 changes: 50 additions & 28 deletions src/shared/utils/generatorSerializedRouteHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EnhancedDevtoolsRoute } from "@/types"
import { RequestHandler } from "msw"
import { HttpMethods, RequestHandler } from "msw"

export const createdUuid = (): string => {
return self.crypto.randomUUID()
Expand All @@ -8,34 +8,56 @@ export const createdUuid = (): string => {
export const generatorSerializedRouteHandlers = (
routes: readonly RequestHandler[]
): EnhancedDevtoolsRoute[] => {
return routes.map((route) => {
console.log(route)
const handlers = Array.isArray((route as any).options)
? (route as any).options.map((option: any) => ({
id: createdUuid(),
response: JSON.stringify(option.response),
status: option.status,
description: option.description,
origin: "msw",
}))
: [
{
return (
routes.map((route) => {
const handlers = Array.isArray((route as any).options)
? (route as any).options.map((option: any) => ({
id: createdUuid(),
response: JSON.stringify((route as any).response),
status: (route as any).status,
description: (route as any).description,
response: JSON.stringify(option.response),
status: option.status,
description: option.description,
origin: "msw",
},
]
return {
}))
: [
{
id: createdUuid(),
response: JSON.stringify((route as any).response),
status: (route as any).status,
description: (route as any).description,
origin: "msw",
},
]
return {
id: createdUuid(),
url: (route.info as any).path,
method: (route.info as any).method,
enabled: (route.info as any).enabled ?? true,
handlers,
delay: 0,
selectedHandlerId: handlers[0]?.id,
}
}) as EnhancedDevtoolsRoute[]
).concat(unknownRoute)
}

/**
* https://mswjs.io/docs/api/setup-worker/reset-handlers
*/
export const unknownRoute: EnhancedDevtoolsRoute = {
id: createdUuid(),
url: "unknown",
method: HttpMethods.GET,
enabled: true,
isHidden: true,
handlers: [
{
id: createdUuid(),
url: (route.info as any).path,
method: (route.info as any).method,
isSkip: (route.info as any).isSkip ?? true,
handlers,
delay: 0,
selectedHandlerId: handlers[0]?.id,
description: "MSW Route (auto-generated)",
}
})
response: "{}",
status: 404,
description: "",
origin: "msw",
},
] as any,
delay: 0,
selectedHandlerId: createdUuid(),
}

0 comments on commit 6b12fbd

Please sign in to comment.