-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcore.ts
More file actions
247 lines (218 loc) · 7.5 KB
/
core.ts
File metadata and controls
247 lines (218 loc) · 7.5 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { type HTTPHeaders } from '@trpc/client';
import { TRPCError } from '@trpc/server';
import {
type NodeHTTPHandlerOptions,
type NodeHTTPResponse,
} from '@trpc/server/adapters/node-http';
import { getErrorShape, TRPCRequestInfo } from '@trpc/server/unstable-core-do-not-import';
import { ZodArray, ZodError, ZodTypeAny } from 'zod';
import { NodeHTTPRequest } from '../../types';
import { generateOpenApiDocument } from '../../generator';
import {
OpenApiErrorResponse,
OpenApiMethod,
OpenApiProcedure,
OpenApiResponse,
OpenApiRouter,
OpenApiSuccessResponse,
} from '../../types';
import {
acceptsRequestBody,
normalizePath,
getInputOutputParsers,
coerceSchema,
instanceofZodTypeLikeVoid,
instanceofZodTypeObject,
instanceofZodTypeOptional,
unwrapZodType,
zodSupportsCoerce,
getContentType,
getRequestSignal,
} from '../../utils';
import { TRPC_ERROR_CODE_HTTP_STATUS, getErrorFromUnknown } from './errors';
import { getBody, getMultipartBody, getQuery } from './input';
import { createProcedureCache } from './procedures';
export type CreateOpenApiNodeHttpHandlerOptions<
TRouter extends OpenApiRouter,
TRequest extends NodeHTTPRequest,
TResponse extends NodeHTTPResponse,
> = Pick<
NodeHTTPHandlerOptions<TRouter, TRequest, TResponse>,
'router' | 'createContext' | 'responseMeta' | 'onError' | 'maxBodySize'
>;
export type OpenApiNextFunction = () => void;
export const createOpenApiNodeHttpHandler = <
TRouter extends OpenApiRouter,
TRequest extends NodeHTTPRequest,
TResponse extends NodeHTTPResponse,
>(
opts: CreateOpenApiNodeHttpHandlerOptions<TRouter, TRequest, TResponse>,
) => {
const router = Object.assign({}, opts.router);
// Validate router
if (process.env.NODE_ENV !== 'production') {
generateOpenApiDocument(router, { title: '', version: '', baseUrl: '' });
}
const { createContext, responseMeta, onError, maxBodySize } = opts;
const getProcedure = createProcedureCache(router);
return async (req: TRequest, res: TResponse, next?: OpenApiNextFunction) => {
const sendResponse = (statusCode: number, headers: HTTPHeaders, body: OpenApiResponse) => {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json');
for (const [key, value] of Object.entries(headers)) {
if (typeof value !== 'undefined') {
res.setHeader(key, value as string);
}
}
res.end(JSON.stringify(body));
};
const method = req.method as OpenApiMethod | 'HEAD';
const reqUrl = req.url!;
const url = new URL(reqUrl.startsWith('/') ? `http://127.0.0.1${reqUrl}` : reqUrl);
const path = normalizePath(url.pathname);
let input: any = undefined;
let ctx: any = undefined;
let info: TRPCRequestInfo | undefined = undefined;
let data: any = undefined;
const { procedure, pathInput } = getProcedure(method, path) ?? {};
try {
if (!procedure) {
if (next) {
return next();
}
// Can be used for warmup
if (method === 'HEAD') {
sendResponse(204, {}, undefined);
return;
}
throw new TRPCError({
message: 'Not found',
code: 'NOT_FOUND',
});
}
const contentType = getContentType(req);
const useBody = acceptsRequestBody(method);
const isMultipart = contentType?.startsWith('multipart/form-data');
if (useBody && !isMultipart && !contentType?.startsWith('application/json')) {
throw new TRPCError({
code: 'UNSUPPORTED_MEDIA_TYPE',
message: contentType
? `Unsupported content-type "${contentType}`
: 'Missing content-type header',
});
}
const { inputParser } = getInputOutputParsers(procedure.procedure);
const unwrappedSchema = unwrapZodType(inputParser, true);
if (isMultipart) {
const formData = await getMultipartBody(req);
if (pathInput) {
for (const [key, value] of Object.entries(pathInput)) {
formData.append(key, value as string);
}
}
input = formData;
} else if (!instanceofZodTypeLikeVoid(unwrappedSchema)) {
// input should stay undefined if z.void()
input = {
...(useBody ? await getBody(req, maxBodySize) : getQuery(req, url)),
...pathInput,
};
}
// if supported, coerce all string values to correct types
if (!isMultipart && zodSupportsCoerce && instanceofZodTypeObject(unwrappedSchema)) {
if (!useBody) {
for (const [key, shape] of Object.entries(unwrappedSchema.shape)) {
let isArray = false;
// Check if it's a direct array
if (shape instanceof ZodArray) {
isArray = true;
}
// Check if it's an optional array
else if (instanceofZodTypeOptional(shape)) {
const innerType = (shape as any).unwrap();
if (innerType instanceof ZodArray) {
isArray = true;
}
}
if (isArray && input[key] !== undefined && !Array.isArray(input[key])) {
input[key] = [input[key]];
}
}
}
coerceSchema(unwrappedSchema);
}
info = {
isBatchCall: false,
accept: null,
calls: [],
type: procedure.type,
connectionParams: null,
signal: getRequestSignal(req, res, maxBodySize),
url,
};
ctx = await createContext?.({ req, res, info });
const caller = router.createCaller(ctx);
const segments = procedure.path.split('.');
const procedureFn = segments.reduce(
(acc, curr) => acc[curr],
caller as any,
) as OpenApiProcedure;
data = await procedureFn(input);
const meta = responseMeta?.({
type: procedure.type,
paths: [procedure.path],
ctx,
data: [data],
errors: [],
info,
eagerGeneration: true,
});
const statusCode = meta?.status ?? 200;
const headers = meta?.headers ?? {};
const body: OpenApiSuccessResponse<typeof data> = data;
sendResponse(statusCode, headers, body);
} catch (cause) {
const error = getErrorFromUnknown(cause);
onError?.({
error,
type: procedure?.type ?? 'unknown',
path: procedure?.path,
input,
ctx,
req,
});
const meta = responseMeta?.({
type: procedure?.type ?? 'unknown',
paths: procedure?.path ? [procedure?.path] : undefined,
ctx,
data: [data],
errors: [error],
info,
eagerGeneration: true,
});
const errorShape = getErrorShape({
config: router._def._config,
error,
type: procedure?.type ?? 'unknown',
path: procedure?.path,
input,
ctx,
});
const isInputValidationError =
error.code === 'BAD_REQUEST' &&
error.cause instanceof Error &&
error.cause.name === 'ZodError';
const statusCode = meta?.status ?? TRPC_ERROR_CODE_HTTP_STATUS[error.code] ?? 500;
const headers = meta?.headers ?? {};
const body: OpenApiErrorResponse = {
...errorShape, // Pass the error through
message: isInputValidationError
? 'Input validation failed'
: (errorShape?.message ?? error.message ?? 'An error occurred'),
code: error.code,
issues: isInputValidationError ? (error.cause as ZodError).issues : undefined,
};
sendResponse(statusCode, headers, body);
}
};
};