trpc-koa-adapter
Version:
Koa adapter for tRPC
34 lines (33 loc) • 1.98 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createKoaMiddleware = void 0;
const node_http_1 = require("@trpc/server/adapters/node-http");
const createKoaMiddleware = (opts) => (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
const { prefix } = opts;
const { req, res, request } = ctx;
if (prefix && !request.path.startsWith(prefix))
return next();
// put parsed body (by koa-bodyparser/@koa/bodyparser for example)
// where nodeHTTPRequestHandler will look for it.
// https://github.com/BlairCurrey/trpc-koa-adapter/issues/24
if ('body' in request) {
req.body = request.body;
}
// koa uses 404 as a default status but some logic in
// nodeHTTPRequestHandler assumes default status of 200.
// https://github.com/trpc/trpc/blob/abc941152b71ff2d68c63156eb5a142174779261/packages/server/src/adapters/node-http/nodeHTTPRequestHandler.ts#L63
res.statusCode = 200;
yield (0, node_http_1.nodeHTTPRequestHandler)(Object.assign(Object.assign({}, opts), { req,
res, path: request.path.slice(((_a = prefix === null || prefix === void 0 ? void 0 : prefix.length) !== null && _a !== void 0 ? _a : 0) + 1) }));
});
exports.createKoaMiddleware = createKoaMiddleware;