Created
December 7, 2022 00:13
-
-
Save anaibol/d8894e6b201bd0e6f1eb2d0a6994da8d to your computer and use it in GitHub Desktop.
Vercel adapter for tRPC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AnyRouter, TRPCError } from "@trpc/server"; | |
import { | |
NodeHTTPCreateContextFnOptions, | |
NodeHTTPHandlerOptions, | |
nodeHTTPRequestHandler, | |
} from "@trpc/server/dist/adapters/node-http"; | |
import { VercelApiHandler, VercelRequest, VercelResponse } from "@vercel/node"; | |
import Cors from "cors"; | |
const cors = Cors(); | |
export type CreateVercelContextOptions = NodeHTTPCreateContextFnOptions< | |
VercelRequest, | |
VercelResponse | |
>; | |
function runMiddleware(req: VercelRequest, res: VercelResponse, fn: any) { | |
return new Promise((resolve, reject) => { | |
fn(req, res, (result: any) => { | |
if (result instanceof Error) { | |
return reject(result); | |
} | |
return resolve(result); | |
}); | |
}); | |
} | |
export function withCors(handler: VercelApiHandler) { | |
return async (req: VercelRequest, res: VercelResponse) => { | |
await runMiddleware(req, res, cors); | |
return await handler(req, res); | |
}; | |
} | |
export function createVercelApiAdapter<TRouter extends AnyRouter>( | |
opts: NodeHTTPHandlerOptions<TRouter, VercelRequest, VercelResponse> | |
): VercelApiHandler { | |
return async (req, res) => { | |
function getPath(): string | null { | |
if (typeof req.query.trpc === "string") { | |
return req.query.trpc; | |
} | |
if (Array.isArray(req.query.trpc)) { | |
return req.query.trpc.join("/"); | |
} | |
return null; | |
} | |
const path = getPath(); | |
if (path === null) { | |
const error = opts.router.getErrorShape({ | |
error: new TRPCError({ | |
message: | |
'Query "trpc" not found - is the file named `[trpc]`.ts or `[...trpc].ts`?', | |
code: "INTERNAL_SERVER_ERROR", | |
}), | |
type: "unknown", | |
ctx: undefined, | |
path: undefined, | |
input: undefined, | |
}); | |
res.statusCode = 500; | |
res.json({ | |
id: -1, | |
error, | |
}); | |
return; | |
} | |
await nodeHTTPRequestHandler({ | |
...opts, | |
req, | |
res, | |
path, | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment