npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

msw-trpc

v2.0.0-beta.1

Published

Trpc API for Mock Service Worker (MSW).

Downloads

130,334

Readme

[!WARNING] You are looking at a pre-release version of msw-trpc, which adds support for msw v2. Documentation may be out of date and bugs might occur, use at your own risk

tPRC support for MSW

  • Create MSW handlers from your tRPC router.
  • Get your tRPC typing into your MSW handlers.
  • Augments MSW with utils for tRPC.

Motivation

As someone who loves MSW and was already using it I wanted to keep using it instead of mocking tRPC. While it is possible to simply write the Rest handlers it felt like it would be great not to lose the full power of tRPC types in the tests.

Usage

1. Install msw-trpc.

npm i msw-trpc --save-dev

2. build your trpcMsw with createTRPCMsw.

import { createTRPCMsw } from 'msw-trpc'
import type { AppRouter } from 'path/to/your/router'

export const trpcMsw = createTRPCMsw<AppRouter>() /* 👈 */

3. Start using it.

const server = setupServer(
  trpcMsw.userById.query((req, res, ctx) => {
    return res(ctx.status(200), ctx.data({ id: '1', name: 'Uncle bob' }))
  }),
  trpcMsw.createUser.mutation(async (req, res, ctx) => {
    return res(ctx.status(200), ctx.data({ id: '2', name: await req.json() }))
  })
)

How it works

createTRPCMsw returns a Proxy that infers types from your AppRouter

// all queries will expose a query function that accepts a MSW handler
trpcMsw.myQuery.query((req, res, ctx) => {})

// all mutations will expose a mutation function that accepts a MSW handler
trpcMsw.myMutation.mutation((req, res, ctx) => {})

supports merged routers

// @filename: routers/_app.ts
// taken from https://trpc.io/docs/merging-routers
import { userRouter } from './user'
import { postRouter } from './post'

const appRouter = router({
  user: userRouter, // put procedures under "user" namespace
  post: postRouter, // put procedures under "post" namespace
})

// @filename: frontend/test/PostList.tsx

// all nested routers will be infered properly
trpcMsw.user.list.query((req, res, ctx) => {})

MSW Augments

ctx.data

Inspired by MSW GraphQL the context of your handlers now exposes a data function that will transform your data to the tRPC structure

mswTrpc.userById.query((req, res, ctx) => {
  console.log(ctx.data({ my: 'data' })) /* 👈 */
})

// return ctx.json with
{
  result: {
    data: {
      my: 'data'
    }
  }
}

req.getInput

Returns the parsed input from the request

//router.ts
const appRouter = t.router({
  userById: t.procedure.input(z.object({ name: z.string() })).query(req => {
    const { input } = req
    const user = userList.find(u => u.name === input.name)
    return user
  }),
})

//test-file.ts
mswTrpc.userById.query((req, res, ctx) => {
  console.log(req.getInput()) /* 👈 */
})

mswTrpc.createUser.mutation(async (req, res, ctx) => {
  console.log(await req.getInput()) /* 👈 in mutation handle getInput returns a promise because it uses req.json() */
})

// outputs
{
  name: 'Pedro'
}

test('should do something', () => {
  trpc.userById.query({ name: 'Pedro' })
})

Please note:

  • calling req.getInput and req.json in the same mutation handler will fail

Config

createTRPCMsw accepts a 2nd argument:

type config = {
  basePath?: string
  baseUrl?: string
  transformer?: {
    input: {
      serialize(object: any): any
      deserialize(object: any): any
    }
    output: {
      serialize(object: any): any
      deserialize(object: any): any
    }
  }
}

| property | default | details | | ----------- | ------------------ | ------------------------------------------------------------------------------------------- | | basePath | 'trpc' | Will match all requests to basePath regardless of host | | baseUrl | undefined | Setting this overrides basePath and will only match requests to this specific baseUrl | | transformer | defaultTransformer | Will transform your output data with transformer.output.serialize when calling ctx.data |

Requirements

Peer dependencies:

  • tRPC server v10 (@trpc/server) must be installed.
  • msw (msw) must be installed.

Please note:

  • Batch is not yet supported
  • Merged routers will match in MSW against . or / (I'm open to PRs on how to only match against . 😊 )
mswTrpc.user.list.query() // this will match /trpc/user/list and /trpc/user.list