Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
cah4a committed Dec 30, 2023
0 parents commit 50c7934
Show file tree
Hide file tree
Showing 10 changed files with 944 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
/dist
.vscode
.idea
.DS_Store
bun.lockb
19 changes: 19 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) Composer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
203 changes: 203 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
# tRPC Bun Adapter

[![npm version](https://badge.fury.io/js/trpc-bun-adapter.svg)](https://badge.fury.io/js/trpc-bun-adapter)
[![License](https://img.shields.io/github/license/cah4a/trpc-bun-adapter)](https://opensource.org/licenses/MIT)

## Description


`trpc-bun-adapter` is a [tRPC](https://trpc.io/) adapter for [Bun](https://github.com/OptimalBits/bun).

Start both HTTP and WebSockets transports with ease.

## Quick Start

Install packages:
```bash
bun install @trpc/server trpc-bun-adapter
```

Create a server.ts file with the following content:
```ts
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:
```bash
bun run server.ts
bun run --watch server.ts # to restart on file changes
```

Check that it works:
```bash
curl http://localhost:3000/ping
```

## API Reference

Ensure you have created a `router.ts` file as outlined in the tRPC documentation: [Define Routers](https://trpc.io/docs/server/routers).

### createBunServeHandler

Creates a Bun serve handler:

```ts
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 fired if it's not a TRPC request
return new Response("Hello world");
},
},
),
);
```

### createBunHttpHandler

Creates a Bun HTTP handler for tRPC HTTP requests:

```ts
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:

```ts
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:

```ts
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:
```ts
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:
```ts
createBunHttpHandler({
router,
createContext,
})
```

Read more documentation about tRPC contexts here: [Contexts](https://trpc.io/docs/server/context)

## License

This project is licensed under the MIT License - see the [LICENSE](https://github.com/cah4a/trpc-bun-adapter/blob/main/LICENSE) file for details.

## Contributing

Contributions are welcome! Feel free to open issues and pull requests.
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "trpc-bun-adapter",
"version": "1.0.0",
"description": "TRPC adapter for bun js runtime",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"scripts": {
"test": "bun test",
"fmt": "bunx @biomejs/biome format --write .",
"build": "npx tsup src/index.ts --format cjs,esm --dts --clean --sourcemap"
},
"keywords": [
"bun",
"trpc",
"adapter",
"websocket"
],
"repository": {
"url": "git+https://github.com/cah4a/trpc-bun-adapter.git"
},
"bugs": "https://github.com/cah4a/trpc-bun-adapter/issues",
"author": "Sancha <cah4o3@gmail.com>",
"license": "MIT",
"devDependencies": {
"@trpc/server": "10.43.0",
"bun-types": "^1.0.20",
"tsup": "^8.0.1",
"typescript": "^5.3.3"
},
"peerDependencies": {
"@trpc/server": "^10.43.0"
}
}
39 changes: 39 additions & 0 deletions src/createBunHttpHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Server } from "bun";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import type { AnyRouter, inferRouterContext } from "@trpc/server";
import type { HTTPBaseHandlerOptions } from "@trpc/server/http";

export type CreateBunContextOptions = { req: Request };

export type BunHttpHandlerOptions<TRouter extends AnyRouter> =
HTTPBaseHandlerOptions<TRouter, Request> & {
endpoint?: string;
createContext?: (
opts: CreateBunContextOptions,
) => inferRouterContext<TRouter> | Promise<inferRouterContext<TRouter>>;
};

export function createBunHttpHandler<TRouter extends AnyRouter>(
opts: BunHttpHandlerOptions<TRouter> & { emitWsUpgrades?: boolean },
) {
return (request: Request, server: Server) => {
const url = new URL(request.url);

if (opts.endpoint && !url.pathname.startsWith(opts.endpoint)) {
return;
}

if (
opts.emitWsUpgrades &&
server.upgrade(request, { data: { req: request } })
) {
return new Response(null, { status: 101 });
}

return fetchRequestHandler({
endpoint: opts.endpoint ?? "",
...opts,
req: request,
});
};
}
33 changes: 33 additions & 0 deletions src/createBunServeHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { ServeOptions, Server } from "bun";
import { createBunWSHandler } from "./createBunWSHandler";
import {
BunHttpHandlerOptions,
createBunHttpHandler,
} from "./createBunHttpHandler";
import type { AnyRouter } from "@trpc/server";

type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;

export function createBunServeHandler<TRouter extends AnyRouter>(
opts: BunHttpHandlerOptions<TRouter>,
serveOptions?: Optional<ServeOptions, "fetch">,
) {
const trpcHandler = createBunHttpHandler({
...opts,
emitWsUpgrades: true,
});

return {
...serveOptions,
async fetch(req: Request, server: Server) {
const trpcReponse = trpcHandler(req, server);

if (trpcReponse) {
return trpcReponse;
}

return serveOptions?.fetch?.call(server, req, server);
},
websocket: createBunWSHandler(opts),
};
}
Loading

0 comments on commit 50c7934

Please sign in to comment.