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

trpc-koa-adapter

v1.2.2

Published

Koa adapter for tRPC

Downloads

27,363

Readme

trpc-koa-adapter

This is an adapter which allows you to mount tRPC onto a Koa server. This is similar to the trpc/packages/server/src/adapters/express.ts adapter.

How to Add tRPC to a Koa Server

Initialize a tRPC router and pass into createKoaMiddleware (along with other desired options). Here is a minimal example:

import Koa from 'koa';
import { createKoaMiddleware } from 'trpc-koa-adapter';
import { initTRPC } from '@trpc/server';

const ALL_USERS = [
  { id: 1, name: 'bob' },
  { id: 2, name: 'alice' },
];

const trpc = initTRPC.create();
const trpcRouter = trpc.router({
  user: trpc.procedure
    .input(Number)
    .output(Object)
    .query((req) => {
      return ALL_USERS.find((user) => req.input === user.id);
    }),
});

const app = new Koa();
const adapter = createKoaMiddleware({
  router: trpcRouter,
  prefix: '/trpc',
});
app.use(adapter);
app.listen(4000);

You can now reach the endpoint with:

curl -X GET "http://localhost:4000/trpc/user?input=1" -H 'content-type: application/json'

Returns:

{ "id": 1, "name": "bob" }

createKoaMiddleware Arguments

The middleware takes a configuration object with the following properties:

| Option | Required | Description | | -------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | router | Required | The tRPC router to mount | | createContext | Optional | A function returning the tRPC context. If defined, the type should be registered on tRPC initialization as shown in an example below and the tRPC docs: https://trpc.io/docs/context | | prefix | Optional | The prefix for tRPC routes, such as /trpc | | nodeHTTPRequestHandler options | Optional | Any of the options used by the underlying request handler. See tRPC's nodeHTTPRequestHandler for more details |

More examples

In addition to these examples, see /example and the implementations in /test/createKoaMiddleware.test.ts.

Using the Context:

const createContext = async ({ req, res }: CreateTrpcKoaContextOptions) => {
  return {
    req,
    res,
    isAuthed: () => req.headers.authorization === 'trustme',
  };
};

type TrpcContext = inferAsyncReturnType<typeof createContext>;

const trpc = initTRPC.context<TrpcContext>().create();

const trpcRouter = trpc.router({
  createUser: trpc.procedure.input(Object).mutation(({ input, ctx }) => {
    // ctx should be fully typed here
    if (!ctx.isAuthed()) {
      ctx.res.statusCode = 401;
      return;
    }

    const newUser = { id: Math.random(), name: input.name };
    ALL_USERS.push(newUser);

    return newUser;
  }),
});

const adapter = createKoaMiddleware({
  router: trpcRouter,
  createContext,
  prefix: '/trpc',
});

Note About Using With a Body Parser:

Using a bodyparser such as @koa/bodyparser, koa-bodyparser, or otherwise parsing the body will consume the data stream on the incoming request. To ensure that tRPC can handle the request, this library looks for the parsed body on ctx.request.body, which is where @koa/bodyparser and koa-bodyparser store the parsed body. If for some reason the parsed body is being stored somewhere else, and you need to parse the body before this middleware, the body will not be available to tRPC and mutations will fail as detailed in this github issue.

Development

The project uses pnpm for package management.

To get started clone the repo, install packages, build, and ensure tests pass:

git clone https://github.com/BlairCurrey/trpc-koa-adapter.git
cd trpc-koa-adapter
pnpm i
pnpm build
pnpm test

Git commit messages must follow conventional commit standard (enforced by husky hooks). Versioning is handle by github actions and is determined by commit messages according to the semantic-release rules and .releaserc configuration.