-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
msw@next #26
base: main
Are you sure you want to change the base?
msw@next #26
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,19 @@ | ||
import { AnyRouter, CombinedDataTransformer, defaultTransformer } from '@trpc/server' | ||
import type { RestRequest } from 'msw' | ||
import { AnyRouter, CombinedDataTransformer, TRPCError, defaultTransformer } from '@trpc/server' | ||
import { getHTTPStatusCodeFromError } from '@trpc/server/http' | ||
|
||
import { rest } from 'msw' | ||
import { HttpResponse, http } from 'msw' | ||
import { MswTrpc } from './types' | ||
import { TRPC_ERROR_CODES_BY_KEY } from '@trpc/server/rpc' | ||
|
||
const getQueryInput = (req: RestRequest, transformer: CombinedDataTransformer) => { | ||
const inputString = req.url.searchParams.get('input') | ||
const getQueryInput = (req: Request, transformer: CombinedDataTransformer) => { | ||
const inputString = new URL(req.url).searchParams.get('input') | ||
|
||
if (inputString == null) return inputString | ||
|
||
return transformer.input.deserialize(JSON.parse(inputString)) | ||
} | ||
|
||
const getMutationInput = async (req: RestRequest, transformer: CombinedDataTransformer) => { | ||
const getMutationInput = async (req: Request, transformer: CombinedDataTransformer) => { | ||
const body = await req.json() | ||
|
||
return transformer.output.deserialize(body) | ||
|
@@ -43,35 +44,35 @@ const createUntypedTRPCMsw = ( | |
{}, | ||
{ | ||
get(_target: unknown, procedureKey) { | ||
if (procedureKey === 'query') { | ||
if (procedureKey === 'query' || procedureKey === 'mutation') { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What would you think of creating an helper for this to clean up the code a bit: const httpMethodByProcedureKey = {
query: http.get,
post: http.post
}
const getInputByProcedureKey = {
query: getQueryInput,
mutation: getMutationInput
}
const createHandler(procedureKey: 'query' | 'mutation') => {
const httpMethod = httpMethodByProcedureKey[procedureKey]
const getInput = getInputByProcedureKey[procedureKey]
return handler => (httpMethod)(
buildUrlFromPathParts(pathParts),
async (params): Promise<any> => {
try {
const body = await handler(await getInput(params.request, transformer))
return HttpResponse.json({ result: { data: transformer.input.serialize(body) } })
} catch (e) {
if (e instanceof TRPCError) {
const status = getHTTPStatusCodeFromError(e)
return HttpResponse.json(
{
error: {
message: e.message,
code: TRPC_ERROR_CODES_BY_KEY[e.code],
data: { code: e.code, httpStatus: status },
},
},
{ status }
)
} else {
throw e
}
}
}
)
} |
||
const getInput = procedureKey === 'query' ? getQueryInput : getMutationInput | ||
// @ts-expect-error any | ||
return handler => | ||
rest.get(buildUrlFromPathParts(pathParts), (req, res, ctx) => { | ||
const augmentedReq = Object.assign(Object.create(Object.getPrototypeOf(req)), req, { | ||
getInput: () => getQueryInput(req, transformer), | ||
}) | ||
|
||
return handler(augmentedReq, res, { | ||
...ctx, | ||
// @ts-expect-error any | ||
data: body => ctx.json({ result: { data: transformer.input.serialize(body) } }), | ||
}) | ||
}) | ||
} | ||
|
||
if (procedureKey === 'mutation') { | ||
// @ts-expect-error any | ||
return handler => | ||
rest.post(buildUrlFromPathParts(pathParts), (req, res, ctx) => { | ||
const augmentedReq = Object.assign(Object.create(Object.getPrototypeOf(req)), req, { | ||
getInput: () => getMutationInput(req, transformer), | ||
}) | ||
return handler(augmentedReq, res, { | ||
...ctx, | ||
// @ts-expect-error any | ||
data: body => ctx.json({ result: { data: transformer.input.serialize(body) } }), | ||
}) | ||
}) | ||
(procedureKey === 'query' ? http.get : http.post)( | ||
buildUrlFromPathParts(pathParts), | ||
async (params): Promise<any> => { | ||
try { | ||
const body = await handler(await getInput(params.request, transformer)) | ||
return HttpResponse.json({ result: { data: transformer.input.serialize(body) } }) | ||
} catch (e) { | ||
if (e instanceof TRPCError) { | ||
const status = getHTTPStatusCodeFromError(e) | ||
return HttpResponse.json( | ||
{ | ||
error: { | ||
message: e.message, | ||
code: TRPC_ERROR_CODES_BY_KEY[e.code], | ||
data: { code: e.code, httpStatus: status }, | ||
}, | ||
}, | ||
{ status } | ||
) | ||
} else { | ||
throw e | ||
} | ||
} | ||
} | ||
) | ||
} | ||
|
||
const newPathParts = | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,29 +11,31 @@ import { | |
|
||
import { setupServer } from 'msw/node' | ||
import { createTRPCMsw } from '../src' | ||
import { TRPCError } from '@trpc/server' | ||
import { TRPCClientError } from '@trpc/client' | ||
|
||
type MswTrpc = typeof mswTrpc | ||
type NestedMswTrpc = typeof nestedMswTrpc | ||
|
||
const setupServerWithQueries = (mswTrpc: MswTrpc, nestedMswTrpc: NestedMswTrpc) => { | ||
return setupServer( | ||
mswTrpc.userById.query((req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '1', name: 'Malo' })) | ||
mswTrpc.userById.query(() => { | ||
return { id: '1', name: 'Malo' } | ||
}), | ||
mswTrpc.userByIdAndPost.query((req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '1', name: 'Malo', posts: ['1'] })) | ||
mswTrpc.userByIdAndPost.query(() => { | ||
return { id: '1', name: 'Malo', posts: ['1'] } | ||
}), | ||
mswTrpc.createUser.mutation(async (req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '2', name: await req.json() })) | ||
mswTrpc.createUser.mutation(name => { | ||
return { id: '2', name } | ||
}), | ||
nestedMswTrpc.users.userById.query((req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '1', name: 'Malo' })) | ||
nestedMswTrpc.users.userById.query(() => { | ||
return { id: '1', name: 'Malo' } | ||
}), | ||
nestedMswTrpc.users.userByIdAndPost.query((req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '1', name: 'Malo', posts: ['1'] })) | ||
nestedMswTrpc.users.userByIdAndPost.query(() => { | ||
return { id: '1', name: 'Malo', posts: ['1'] } | ||
}), | ||
nestedMswTrpc.users.createUser.mutation(async (req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data({ id: '2', name: await req.json() })) | ||
nestedMswTrpc.users.createUser.mutation(name => { | ||
return { id: '2', name } | ||
}) | ||
) | ||
} | ||
|
@@ -76,6 +78,17 @@ describe('queries and mutations', () => { | |
expect(user).toEqual({ id: '2', name: 'Robert' }) | ||
}) | ||
}) | ||
|
||
test('throwing error works', async () => { | ||
server.use( | ||
mswTrpc.userById.query(() => { | ||
throw new TRPCError({ code: 'BAD_REQUEST' }) | ||
}) | ||
) | ||
await expect(async () => { | ||
await trpc.userById.query('1') | ||
}).rejects.toThrow(new TRPCClientError('BAD_REQUEST')) | ||
}) | ||
}) | ||
Comment on lines
+82
to
92
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is the API for returning 404, to throw a |
||
|
||
describe('config', () => { | ||
|
@@ -124,12 +137,11 @@ describe('config', () => { | |
|
||
describe('with SuperJson transformer', () => { | ||
const serverWithSuperJson = setupServer( | ||
mswTrpcWithSuperJson.listUsers.query((req, res, ctx) => { | ||
return res(ctx.status(200), ctx.data(req.getInput())) | ||
mswTrpcWithSuperJson.listUsers.query(users => { | ||
return users | ||
}), | ||
mswTrpcWithSuperJson.createFriend.mutation(async (req, res, ctx) => { | ||
const input = await req.getInput() | ||
return res(ctx.status(200), ctx.data({ name: input.name, id: 'new-friend' })) | ||
mswTrpcWithSuperJson.createFriend.mutation(async ({ name }) => { | ||
return { name, id: 'new-friend' } | ||
}) | ||
) | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Set dependency to ^2.0.0