Skip to content
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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jest-environment-jsdom',
testEnvironment: 'node',
rootDir: './test',
snapshotFormat: {
escapeString: true,
Expand Down
6,665 changes: 1,264 additions & 5,401 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,17 @@
"expect-type": "^0.15.0",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"msw": "^1.0.1",
"msw": "next",
"prettier": "^2.8.3",
"rimraf": "^4.1.1",
"superjson": "^1.12.2",
"ts-jest": "^29.0.5",
"ts-node": "^10.9.1",
"typescript": "^4.9.5",
"whatwg-fetch": "^3.6.2",
"zod": "^3.20.2"
},
"peerDependencies": {
"@trpc/server": ">=10.9.0",
"msw": ">=0.49.3"
"msw": "next"
Copy link
Owner

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

}
}
67 changes: 34 additions & 33 deletions src/createTRPCMsw.ts
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)
Expand Down Expand Up @@ -43,35 +44,35 @@ const createUntypedTRPCMsw = (
{},
{
get(_target: unknown, procedureKey) {
if (procedureKey === 'query') {
if (procedureKey === 'query' || procedureKey === 'mutation') {
Copy link
Owner

Choose a reason for hiding this comment

The 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 =
Expand Down
56 changes: 16 additions & 40 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import { AnyRouter, BuildProcedure, Procedure, ProcedureParams, ProcedureType, inferRouterInputs } from '@trpc/server'
import {
DefaultBodyType,
MockedRequest,
PathParams,
ResponseResolver,
ResponseTransformer,
RestContext,
RestHandler,
RestRequest,
} from 'msw'

export type ContextWithDataTransformer<T> = RestContext & {
data: (
data: T extends Procedure<ProcedureType, infer ProcedureParams> ? ProcedureParams['_output_out'] : never
) => ResponseTransformer<DefaultBodyType, any>
}
import { DefaultBodyType, RequestHandler } from 'msw'
import { RequestHandlerDefaultInfo } from 'msw/lib/core/handlers/RequestHandler'

export type ExtractKeys<T, K extends keyof T = keyof T> = T[K] extends
| BuildProcedure<'query', any, any>
Expand All @@ -29,37 +15,27 @@ export type ExtractInput<T extends ProcedureParams> = T extends ProcedureParams<
: DefaultBodyType
: never

export type WithQueryInput<T, K extends keyof T = keyof T> = {
getInput: () => T[K] extends BuildProcedure<any, any, any>
? T extends AnyRouter
? inferRouterInputs<T>[K]
: never
export type ExtractOutput<T> = T extends Procedure<ProcedureType, infer ProcedureParams>
? ProcedureParams['_output_out'] extends DefaultBodyType
? ProcedureParams['_output_out']
: never
}
: never

export type WithMutationInput<T, K extends keyof T = keyof T> = {
getInput: () => T[K] extends BuildProcedure<any, any, any>
? T extends AnyRouter
? Promise<inferRouterInputs<T>[K]>
: never
export type WithInput<T, K extends keyof T = keyof T> = T[K] extends BuildProcedure<any, any, any>
? T extends AnyRouter
? inferRouterInputs<T>[K]
: never
}
: never

type PromiseOrValue<T> = T | Promise<T>

export type SetQueryHandler<T, K extends keyof T> = (
handler: ResponseResolver<
RestRequest<never, PathParams<string>> & WithQueryInput<T, K>,
ContextWithDataTransformer<T[K]>,
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
handler: (input: WithInput<T, K>) => PromiseOrValue<ExtractOutput<T[K]>>
) => RequestHandler

export type SetMutationHandler<T, K extends keyof T> = (
handler: ResponseResolver<
RestRequest<T[K] extends BuildProcedure<any, infer P, any> ? ExtractInput<P> : DefaultBodyType, PathParams> &
WithMutationInput<T, K>,
ContextWithDataTransformer<T[K]>
>
) => RestHandler<MockedRequest<DefaultBodyType>>
handler: (input: WithInput<T, K>) => PromiseOrValue<ExtractOutput<T[K]>>
) => RequestHandler

export type Query<T, K extends keyof T> = {
query: SetQueryHandler<T, K>
Expand Down
80 changes: 9 additions & 71 deletions test/createTRPCMsw.test.ts
Original file line number Diff line number Diff line change
@@ -1,115 +1,53 @@
import { expectTypeOf } from 'expect-type'
import {
ResponseResolver,
RestRequest,
PathParams,
DefaultBodyType,
RestHandler,
MockedRequest,
RestContext,
ResponseTransformer,
} from 'msw'
import { RequestHandler } from 'msw'
import { mswTrpc, mswTrpcWithSuperJson, nestedMswTrpc, User } from './setup'

type PromiseOrValue<T> = T | Promise<T>
describe('proxy returned by createMswTrpc', () => {
it('should expose property query on properties that match TRPC query procedures', () => {
expectTypeOf(mswTrpc.userById.query).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<never, PathParams<string>> & { getInput: () => string },
RestContext & {
data: (data: User | undefined) => ResponseTransformer<DefaultBodyType, any>
},
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User | undefined>) => RequestHandler
>()
})

it('should expose property mutation on properties that match TRPC mutation procedures', () => {
expectTypeOf(mswTrpc.createUser.mutation).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<string, PathParams> & { getInput: () => Promise<string> },
RestContext & {
data: (data: User) => ResponseTransformer<DefaultBodyType, any>
}
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User>) => RequestHandler
>()
})

describe('with merged routers', () => {
it('should expose property query on properties that match TRPC query procedures', () => {
expectTypeOf(nestedMswTrpc.users.userById.query).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<never, PathParams<string>> & { getInput: () => string },
RestContext & {
data: (data: User | undefined) => ResponseTransformer<DefaultBodyType, any>
},
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User | undefined>) => RequestHandler
>()
})
})

describe('with transformer', () => {
it('context.data should return the correct type', () => {
expectTypeOf(mswTrpcWithSuperJson.createUser.mutation).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<string, PathParams> & { getInput: () => Promise<string> },
RestContext & {
data: (data: User) => ResponseTransformer<DefaultBodyType, any>
}
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User>) => RequestHandler
>()
})

it('req.getInput should return the correct type', () => {
expectTypeOf(mswTrpcWithSuperJson.userById.query).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<never, PathParams<string>> & { getInput: () => string },
RestContext & {
data: (data: User | undefined) => ResponseTransformer<DefaultBodyType, any>
},
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User | undefined>) => RequestHandler
>()
})
})

describe('with output transformer', () => {
it('query context.data should consider output transformer', () => {
expectTypeOf(mswTrpc.userByName.query).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<never, PathParams<string>> & { getInput: () => string },
RestContext & {
data: (data: User | undefined) => ResponseTransformer<DefaultBodyType, any>
},
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: string) => PromiseOrValue<User | undefined>) => RequestHandler
>()
})

it('mutation context.data should consider output transformer', () => {
expectTypeOf(mswTrpc.updateUser.mutation).toEqualTypeOf<
(
handler: ResponseResolver<
RestRequest<User, PathParams> & { getInput: () => Promise<User> },
RestContext & {
data: (data: User) => ResponseTransformer<DefaultBodyType, any>
},
DefaultBodyType
>
) => RestHandler<MockedRequest<DefaultBodyType>>
(handler: (input: User) => PromiseOrValue<User>) => RequestHandler
>()
})
})
Expand Down
46 changes: 29 additions & 17 deletions test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
})
)
}
Expand Down Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the API for returning 404, to throw a NOT_FOUND TRPCError?


describe('config', () => {
Expand Down Expand Up @@ -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' }
})
)

Expand Down
Loading