UNPKG

@trpc/server

Version:

The tRPC server library

72 lines (70 loc) • 2.3 kB
import { m as run } from "../codes-nbrm_zWY.mjs"; import { n as _objectSpread2 } from "../getErrorShape-B5jPKHJ3.mjs"; import { n as nodeHTTPRequestHandler, r as createURL, t as internal_exceptionHandler } from "../node-http-Df_b1FfK.mjs"; import http from "http"; //#region src/adapters/standalone.ts /** * If you're making an adapter for tRPC and looking at this file for reference, you should import types and functions from `@trpc/server` and `@trpc/server/http` * * @example * ```ts * import type { AnyTRPCRouter } from '@trpc/server' * import type { HTTPBaseHandlerOptions } from '@trpc/server/http' * ``` */ const trimSlashes = (path) => { path = path.startsWith("/") ? path.slice(1) : path; path = path.endsWith("/") ? path.slice(0, -1) : path; return path; }; function createHandler(opts) { var _opts$basePath; const basePath = trimSlashes((_opts$basePath = opts.basePath) !== null && _opts$basePath !== void 0 ? _opts$basePath : "/"); return (req, res) => { let path = ""; run(async () => { const url = createURL(req); path = trimSlashes(trimSlashes(url.pathname).slice(basePath.length)); await nodeHTTPRequestHandler(_objectSpread2(_objectSpread2({}, opts), {}, { req, res, path })); }).catch(internal_exceptionHandler(_objectSpread2({ req, res, path }, opts))); }; } /** * Creates a Node.js request listener for a router, to use with your own * `http.createServer()`. * @see https://trpc.io/docs/server/adapters/standalone#adding-a-handler-to-a-custom-http-server * @internal */ function createHTTPHandler(opts) { return createHandler(opts); } /** * Creates a Node.js HTTP server for a router. Call `.listen()` on it. * @example * ```ts * createHTTPServer({ router: appRouter, createContext }).listen(3000); * ``` * @see https://trpc.io/docs/server/adapters/standalone#2-use-the-standalone-adapter */ function createHTTPServer(opts) { return http.createServer(createHTTPHandler(opts)); } /** * Creates a request listener for a router, to use with Node.js's * `http2.createSecureServer()`. * @see https://trpc.io/docs/server/adapters/standalone#http2 */ function createHTTP2Handler(opts) { return createHandler(opts); } //#endregion export { createHTTP2Handler, createHTTPHandler, createHTTPServer }; //# sourceMappingURL=standalone.mjs.map