This repository was archived by the owner on Nov 19, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathnext.ts
58 lines (49 loc) · 1.65 KB
/
next.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { TRPCError } from '@trpc/server';
import { NextApiRequest, NextApiResponse } from 'next';
import { OpenApiErrorResponse, OpenApiRouter } from '../types';
import { normalizePath } from '../utils/path';
import {
CreateOpenApiNodeHttpHandlerOptions,
createOpenApiNodeHttpHandler,
} from './node-http/core';
export type CreateOpenApiNextHandlerOptions<TRouter extends OpenApiRouter> = Omit<
CreateOpenApiNodeHttpHandlerOptions<TRouter, NextApiRequest, NextApiResponse>,
'maxBodySize'
>;
export const createOpenApiNextHandler = <TRouter extends OpenApiRouter>(
opts: CreateOpenApiNextHandlerOptions<TRouter>,
) => {
const openApiHttpHandler = createOpenApiNodeHttpHandler(opts);
return async (req: NextApiRequest, res: NextApiResponse) => {
let pathname: string | null = null;
if (typeof req.query.trpc === 'string') {
pathname = req.query.trpc;
} else if (Array.isArray(req.query.trpc)) {
pathname = req.query.trpc.join('/');
}
if (pathname === null) {
const error = new TRPCError({
message: 'Query "trpc" not found - is the `trpc-openapi` file named `[...trpc].ts`?',
code: 'INTERNAL_SERVER_ERROR',
});
opts.onError?.({
error,
type: 'unknown',
path: undefined,
input: undefined,
ctx: undefined,
req,
});
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
const body: OpenApiErrorResponse = {
message: error.message,
code: error.code,
};
res.end(JSON.stringify(body));
return;
}
req.url = normalizePath(pathname);
await openApiHttpHandler(req, res);
};
};