Code Monkey home page Code Monkey logo

trpc-bun-adapter's Introduction

tRPC Bun Adapter

npm version License

Description

trpc-bun-adapter is a tRPC adapter for Bun.

Start both HTTP and WebSockets transports with ease.

Quick Start

Install packages:

bun install @trpc/server trpc-bun-adapter

Create a server.ts file with the following content:

import {initTRPC} from '@trpc/server';
import {createBunServeHandler} from 'trpc-bun-adapter';

const t = initTRPC.create();

export const router = t.router({
    ping: t.procedure.query(() => "pong"),
});

Bun.serve(createBunServeHandler({ router }));

To start the server, run:

bun run server.ts
bun run --watch server.ts # to restart on file changes

Check that it works:

curl http://localhost:3000/ping

Example

for a full example, see the example directory.

API Reference

Ensure you have created a router.ts file as outlined in the tRPC documentation: Define Routers.

createBunServeHandler

Creates a Bun serve handler:

import {createBunServeHandler, CreateBunContextOptions} from 'trpc-bun-adapter';
import {router} from './router';

const createContext = (opts: CreateBunContextOptions) => ({
    user: 1,
});

Bun.serve(
    createBunServeHandler(
        {
            router,
            // optional arguments:
            endpoint: '/trpc', // Default to ""
            createContext,
            onError: console.error,
            responseMeta(opts) {
                return {
                    status: 202,
                    headers: {},
                }
            },
            batching: {
                enabled: true,
            },
        },
        {
            // Bun serve options
            port: 3001,
            fetch(request, server) {
                // will be executed if it's not a TRPC request
                return new Response("Hello world");
            },
        },
    ),
);

To add response headers like Cross-origin resource sharing (CORS) use responseMeta option:

Bun.serve(
   createBunServeHandler({
         router: appRouter,
         responseMeta(opts) {
            return {
               status: 200,
               headers: {
                  "Access-Control-Allow-Origin": "*",
                  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
                  "Access-Control-Allow-Headers": "Content-Type, Authorization"
               }
            };
         }
      }
   )
);

createBunHttpHandler

Creates a Bun HTTP handler for tRPC HTTP requests:

import {createBunHttpHandler, CreateBunContextOptions} from 'trpc-bun-adapter';
import {router} from './router';

const createContext = (opts: CreateBunContextOptions) => ({
    user: 1,
});

const bunHandler = createBunHttpHandler({
    router,
    // optional arguments:
    endpoint: '/trpc', // Default to ""
    createContext,
    onError: console.error,
    responseMeta(opts) {
        return {
            status: 202,
            headers: {},
        }
    },
    batching: {
        enabled: true,
    },
    emitWsUpgrades: false, // pass true to upgrade to WebSocket
});

Bun.serve({
    fetch(request, response) {
        return bunHandler(request, response) ?? new Response("Not found", {status: 404});
    }
});

createBunWsHandler

Creates a Bun WebSocket handler for tRPC websocket requests:

import { createBunWSHandler, CreateBunContextOptions } from './src';
import { router } from './router';

const createContext = (opts: CreateBunContextOptions) => ({
    user: 1,
});

const websocket = createBunWSHandler({
    router,
    // optional arguments:
    createContext,
    onError: console.error,
    batching: {
        enabled: true,
    },
});

Bun.serve({
    fetch(request, server) {
        if (server.upgrade(request, {data: {req: request}})) {
            return;
        }

        return new Response("Please use websocket protocol", {status: 404});
    },
    websocket,
});

CreateBunContextOptions

To ensure your router recognizes the context type, define a createContext function utilizing the CreateBunContextOptions type:

import { initTRPC } from '@trpc/server';
import type { CreateBunContextOptions } from "src/createBunHttpHandler";

export const createContext = async (opts: CreateBunContextOptions) => {
    return {
        authorization: req.headers.get('Authorization')
    };
};

With createContext defined, you can use it in your router to access the context, such as the authorization information:

const t = initTRPC.context<typeof createContext>().create();

export const router = t.router({
    session: t.procedure.query(({ ctx }) => ctx.authorization),
});

Finally, pass your createContext function besides router to createBunHttpHandler. This integrates your custom context into the HTTP handler setup:

createBunHttpHandler({
    router,
    createContext,
})

Read more documentation about tRPC contexts here: Contexts

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Feel free to open issues and pull requests.

trpc-bun-adapter's People

Contributors

cah4a avatar ceopaludetto avatar juliusmarminge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

trpc-bun-adapter's Issues

Types mismatches for tRPC +11.0.0-rc455

Hey guys, thanks for creating and maintaining this package.

I'm having following typescript errors for the latest trpc version
'@trpc/client': 11.0.0-rc.466
'@trpc/server': 11.0.0-rc.466

but I recall it don't work for last at least two weeks.

Argument of type '{ endpoint: string; router: BuiltRouter<{ ctx: object; meta: object; errorShape: DefaultErrorShape; transformer: false; }, { ping: QueryProcedure<{ input: void; output: string; }>; subscribe: SubscriptionProcedure<...>; }>; }' is not assignable to parameter of type 'BunHttpHandlerOptions<BuiltRouter<{ ctx: object; meta: object; errorShape: DefaultErrorShape; transformer: false; }, { ping: QueryProcedure<{ input: void; output: string; }>; subscribe: SubscriptionProcedure<...>; }>>'.
Property 'req' is missing in type '{ endpoint: string; router: BuiltRouter<{ ctx: object; meta: object; errorShape: DefaultErrorShape; transformer: false; }, { ping: QueryProcedure<{ input: void; output: string; }>; subscribe: SubscriptionProcedure<...>; }>; }' but required in type '{ req: Request; endpoint: string; }'.ts(2345)

Example

Hii can you create a demo example folder using http and websocket with ping/pong for both thanks.

Support `resHeaders` in context

@trpc/server/adapters/fetch recently added support to resHeaders in the context, this allow adding headers to the response inside query or mutations, since the createContext is just forwarded to the fetchRequestHandler I don't see any problem if we support as well. Actually we just need to change the CreateBunContextOptions with the FetchCreateContextFnOptions imported from @trpc/server/adapters/fetch. I've patched locally and everything works flawlessly

Documentation: setting-up CORS

Hi,
I'm new to trpc and I couldn't set up CORS in server.ts

Is there a possiblity to add this into documentation?

I was reading the documentation on cors. It mentions that:
"You also need to enable CORS on your server by modifying your adapter, or the HTTP server which fronts your API. The best way to do this varies adapter-by-adapter and based on your hosting infrastructure, and individual adapters generally document this process where applicable."

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.