-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolveHTTPResponse.ts
264 lines (242 loc) · 6.65 KB
/
resolveHTTPResponse.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import {
AnyRouter,
ProcedureType,
callProcedure,
inferRouterContext,
inferRouterError,
} from '../core';
import { TRPCError } from '../error/TRPCError';
import { getCauseFromUnknown, getTRPCErrorFromUnknown } from '../error/utils';
import { transformTRPCResponse } from '../internals/transformTRPCResponse';
import { TRPCResponse } from '../rpc';
import { Maybe } from '../types';
import { getHTTPStatusCode } from './getHTTPStatusCode';
import {
HTTPBaseHandlerOptions,
HTTPHeaders,
HTTPRequest,
HTTPResponse,
} from './internals/types';
const HTTP_METHOD_PROCEDURE_TYPE_MAP: Record<
string,
ProcedureType | undefined
> = {
GET: 'query',
POST: 'mutation',
};
function getRawProcedureInputOrThrow(req: HTTPRequest) {
try {
if (req.method === 'GET') {
if (!req.query.has('input')) {
return undefined;
}
const raw = req.query.get('input');
return JSON.parse(raw!);
}
if (typeof req.body === 'string') {
// A mutation with no inputs will have req.body === ''
return req.body.length === 0 ? undefined : JSON.parse(req.body);
}
return req.body;
} catch (err) {
throw new TRPCError({
code: 'PARSE_ERROR',
cause: getCauseFromUnknown(err),
});
}
}
interface ResolveHTTPRequestOptions<
TRouter extends AnyRouter,
TRequest extends HTTPRequest,
> extends HTTPBaseHandlerOptions<TRouter, TRequest> {
createContext: () => Promise<inferRouterContext<TRouter>>;
req: TRequest;
path: string;
error?: Maybe<TRPCError>;
}
export async function resolveHTTPResponse<
TRouter extends AnyRouter,
TRequest extends HTTPRequest,
>(opts: ResolveHTTPRequestOptions<TRouter, TRequest>): Promise<HTTPResponse> {
const { createContext, onError, router, req } = opts;
const batchingEnabled = opts.batching?.enabled ?? true;
if (req.method === 'HEAD') {
// can be used for lambda warmup
return {
status: 204,
};
}
const type =
HTTP_METHOD_PROCEDURE_TYPE_MAP[req.method] ?? ('unknown' as const);
let ctx: inferRouterContext<TRouter> | undefined = undefined;
let paths: string[] | undefined = undefined;
const isBatchCall = !!req.query.get('batch');
type TRouterError = inferRouterError<TRouter>;
type TRouterResponse = TRPCResponse<unknown, TRouterError>;
function endResponse(
untransformedJSON: TRouterResponse | TRouterResponse[],
errors: TRPCError[],
): HTTPResponse {
let status = getHTTPStatusCode(untransformedJSON);
const headers: HTTPHeaders = {
'Content-Type': 'application/json',
};
const meta =
opts.responseMeta?.({
ctx,
paths,
type,
data: Array.isArray(untransformedJSON)
? untransformedJSON
: [untransformedJSON],
errors,
}) ?? {};
for (const [key, value] of Object.entries(meta.headers ?? {})) {
headers[key] = value;
}
if (meta.status) {
status = meta.status;
}
const transformedJSON = transformTRPCResponse(router, untransformedJSON);
const body = JSON.stringify(transformedJSON);
return {
body,
status,
headers,
};
}
try {
if (opts.error) {
throw opts.error;
}
if (isBatchCall && !batchingEnabled) {
throw new Error(`Batching is not enabled on the server`);
}
/* istanbul ignore if */
if (type === 'subscription') {
throw new TRPCError({
message: 'Subscriptions should use wsLink',
code: 'METHOD_NOT_SUPPORTED',
});
}
if (type === 'unknown') {
throw new TRPCError({
message: `Unexpected request method ${req.method}`,
code: 'METHOD_NOT_SUPPORTED',
});
}
const rawInput = getRawProcedureInputOrThrow(req);
paths = isBatchCall ? opts.path.split(',') : [opts.path];
ctx = await createContext();
const deserializeInputValue = (rawValue: unknown) => {
return typeof rawValue !== 'undefined'
? router._def._config.transformer.input.deserialize(rawValue)
: rawValue;
};
const getInputs = (): Record<number, unknown> => {
if (!isBatchCall) {
return {
0: deserializeInputValue(rawInput),
};
}
/* istanbul ignore if */
if (
rawInput == null ||
typeof rawInput !== 'object' ||
Array.isArray(rawInput)
) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '"input" needs to be an object when doing a batch call',
});
}
const input: Record<number, unknown> = {};
for (const key in rawInput) {
const k = key as any as number;
const rawValue = rawInput[k];
const value = deserializeInputValue(rawValue);
input[k] = value;
}
return input;
};
const inputs = getInputs();
const rawResults = await Promise.all(
paths.map(async (path, index) => {
const input = inputs[index];
try {
const output = await callProcedure({
procedures: router._def.procedures,
path,
rawInput: input,
ctx,
type,
});
return {
input,
path,
data: output,
};
} catch (cause) {
const error = getTRPCErrorFromUnknown(cause);
onError?.({ error, path, input, ctx, type: type, req });
return {
input,
path,
error,
};
}
}),
);
const errors = rawResults.flatMap((obj) => (obj.error ? [obj.error] : []));
const resultEnvelopes = rawResults.map((obj): TRouterResponse => {
const { path, input } = obj;
if (obj.error) {
return {
error: router.getErrorShape({
error: obj.error,
type,
path,
input,
ctx,
}),
};
} else {
return {
result: {
data: obj.data,
},
};
}
});
const result = isBatchCall ? resultEnvelopes : resultEnvelopes[0]!;
return endResponse(result, errors);
} catch (cause) {
// we get here if
// - batching is called when it's not enabled
// - `createContext()` throws
// - post body is too large
// - input deserialization fails
const error = getTRPCErrorFromUnknown(cause);
onError?.({
error,
path: undefined,
input: undefined,
ctx,
type: type,
req,
});
return endResponse(
{
error: router.getErrorShape({
error,
type,
path: undefined,
input: undefined,
ctx,
}),
},
[error],
);
}
}