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 pathschema.ts
218 lines (193 loc) · 6.16 KB
/
schema.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
import { TRPCError } from '@trpc/server';
import { OpenAPIV3 } from 'openapi-types';
import { z } from 'zod';
import zodToJsonSchema from 'zod-to-json-schema';
import { OpenApiContentType } from '../types';
import {
instanceofZodType,
instanceofZodTypeCoercible,
instanceofZodTypeLikeString,
instanceofZodTypeLikeVoid,
instanceofZodTypeObject,
instanceofZodTypeOptional,
unwrapZodType,
zodSupportsCoerce,
} from '../utils/zod';
const zodSchemaToOpenApiSchemaObject = (zodSchema: z.ZodType): OpenAPIV3.SchemaObject => {
// FIXME: https://github.com/StefanTerdell/zod-to-json-schema/issues/35
return zodToJsonSchema(zodSchema, { target: 'openApi3', $refStrategy: 'none', pipeStrategy: 'output' }) as any;
};
export const getParameterObjects = (
schema: unknown,
pathParameters: string[],
inType: 'all' | 'path' | 'query',
example: Record<string, any> | undefined,
): OpenAPIV3.ParameterObject[] | undefined => {
if (!instanceofZodType(schema)) {
throw new TRPCError({
message: 'Input parser expects a Zod validator',
code: 'INTERNAL_SERVER_ERROR',
});
}
const isRequired = !schema.isOptional();
const unwrappedSchema = unwrapZodType(schema, true);
if (pathParameters.length === 0 && instanceofZodTypeLikeVoid(unwrappedSchema)) {
return undefined;
}
if (!instanceofZodTypeObject(unwrappedSchema)) {
throw new TRPCError({
message: 'Input parser must be a ZodObject',
code: 'INTERNAL_SERVER_ERROR',
});
}
const shape = unwrappedSchema.shape;
const shapeKeys = Object.keys(shape);
for (const pathParameter of pathParameters) {
if (!shapeKeys.includes(pathParameter)) {
throw new TRPCError({
message: `Input parser expects key from path: "${pathParameter}"`,
code: 'INTERNAL_SERVER_ERROR',
});
}
}
return shapeKeys
.filter((shapeKey) => {
const isPathParameter = pathParameters.includes(shapeKey);
if (inType === 'path') {
return isPathParameter;
} else if (inType === 'query') {
return !isPathParameter;
}
return true;
})
.map((shapeKey) => {
let shapeSchema = shape[shapeKey]!;
const isShapeRequired = !shapeSchema.isOptional();
const isPathParameter = pathParameters.includes(shapeKey);
if (!instanceofZodTypeLikeString(shapeSchema)) {
if (zodSupportsCoerce) {
if (!instanceofZodTypeCoercible(shapeSchema)) {
throw new TRPCError({
message: `Input parser key: "${shapeKey}" must be ZodString, ZodNumber, ZodBoolean, ZodBigInt or ZodDate`,
code: 'INTERNAL_SERVER_ERROR',
});
}
} else {
throw new TRPCError({
message: `Input parser key: "${shapeKey}" must be ZodString`,
code: 'INTERNAL_SERVER_ERROR',
});
}
}
if (instanceofZodTypeOptional(shapeSchema)) {
if (isPathParameter) {
throw new TRPCError({
message: `Path parameter: "${shapeKey}" must not be optional`,
code: 'INTERNAL_SERVER_ERROR',
});
}
shapeSchema = shapeSchema.unwrap();
}
const { description, ...openApiSchemaObject } = zodSchemaToOpenApiSchemaObject(shapeSchema);
return {
name: shapeKey,
in: isPathParameter ? 'path' : 'query',
required: isPathParameter || (isRequired && isShapeRequired),
schema: openApiSchemaObject,
description: description,
example: example?.[shapeKey],
};
});
};
export const getRequestBodyObject = (
schema: unknown,
pathParameters: string[],
contentTypes: OpenApiContentType[],
example: Record<string, any> | undefined,
): OpenAPIV3.RequestBodyObject | undefined => {
if (!instanceofZodType(schema)) {
throw new TRPCError({
message: 'Input parser expects a Zod validator',
code: 'INTERNAL_SERVER_ERROR',
});
}
const isRequired = !schema.isOptional();
const unwrappedSchema = unwrapZodType(schema, true);
if (pathParameters.length === 0 && instanceofZodTypeLikeVoid(unwrappedSchema)) {
return undefined;
}
if (!instanceofZodTypeObject(unwrappedSchema)) {
throw new TRPCError({
message: 'Input parser must be a ZodObject',
code: 'INTERNAL_SERVER_ERROR',
});
}
// remove path parameters
const mask: Record<string, true> = {};
const dedupedExample = example && { ...example };
pathParameters.forEach((pathParameter) => {
mask[pathParameter] = true;
if (dedupedExample) {
delete dedupedExample[pathParameter];
}
});
const dedupedSchema = unwrappedSchema.omit(mask);
// if all keys are path parameters
if (pathParameters.length > 0 && Object.keys(dedupedSchema.shape).length === 0) {
return undefined;
}
const openApiSchemaObject = zodSchemaToOpenApiSchemaObject(dedupedSchema);
const content: OpenAPIV3.RequestBodyObject['content'] = {};
for (const contentType of contentTypes) {
content[contentType] = {
schema: openApiSchemaObject,
example: dedupedExample,
};
}
return {
required: isRequired,
content,
};
};
export const errorResponseObject: OpenAPIV3.ResponseObject = {
description: 'Error response',
content: {
'application/json': {
schema: zodSchemaToOpenApiSchemaObject(
z.object({
message: z.string(),
code: z.string(),
issues: z.array(z.object({ message: z.string() })).optional(),
}),
),
},
},
};
export const getResponsesObject = (
schema: unknown,
example: Record<string, any> | undefined,
headers: Record<string, OpenAPIV3.HeaderObject | OpenAPIV3.ReferenceObject> | undefined
): OpenAPIV3.ResponsesObject => {
if (!instanceofZodType(schema)) {
throw new TRPCError({
message: 'Output parser expects a Zod validator',
code: 'INTERNAL_SERVER_ERROR',
});
}
const successResponseObject: OpenAPIV3.ResponseObject = {
description: 'Successful response',
headers: headers,
content: {
'application/json': {
schema: zodSchemaToOpenApiSchemaObject(schema),
example,
},
},
};
return {
200: successResponseObject,
default: {
$ref: '#/components/responses/error',
},
};
};