-
Notifications
You must be signed in to change notification settings - Fork 29
/
common-helpers.ts
247 lines (225 loc) · 6.73 KB
/
common-helpers.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
import { Request } from "express";
import { HttpError } from "http-errors";
import { z } from "zod";
import {
CommonConfig,
InputSources,
LoggerConfig,
loggerLevels,
} from "./config-type";
import { IOSchema } from "./io-schema";
import { getMeta } from "./metadata";
import { AuxMethod, Method } from "./method";
import { mimeMultipart } from "./mime";
import { ZodUpload } from "./upload-schema";
export type FlatObject = Record<string, any>;
export type ArrayElement<T extends readonly unknown[]> =
T extends readonly (infer K)[] ? K : never;
/** @see https://expressjs.com/en/guide/routing.html */
export const routePathParamsRegex = /:([A-Za-z0-9_]+)/g;
function areFilesAvailable(request: Request) {
const contentType = request.header("content-type") || "";
const isMultipart =
contentType.slice(0, mimeMultipart.length).toLowerCase() === mimeMultipart;
return "files" in request && isMultipart;
}
export const defaultInputSources: InputSources = {
get: ["query", "params"],
post: ["body", "params", "files"],
put: ["body", "params"],
patch: ["body", "params"],
delete: ["body", "query", "params"],
};
const fallbackInputSource = defaultInputSources.delete;
export const getActualMethod = (request: Request) =>
request.method.toLowerCase() as Method | AuxMethod;
export function getInput(
request: Request,
inputAssignment: CommonConfig["inputSources"]
): any {
const method = getActualMethod(request);
if (method === "options") {
return {};
}
let props = fallbackInputSource;
if (method in defaultInputSources) {
props = defaultInputSources[method];
}
if (inputAssignment && method in inputAssignment) {
props = inputAssignment[method] || props;
}
return props
.filter((prop) => (prop === "files" ? areFilesAvailable(request) : true))
.reduce(
(carry, prop) => ({
...carry,
...request[prop],
}),
{}
);
}
export function isLoggerConfig(logger: any): logger is LoggerConfig {
return (
typeof logger === "object" &&
"level" in logger &&
"color" in logger &&
Object.keys(loggerLevels).includes(logger.level) &&
typeof logger.color === "boolean"
);
}
export function isValidDate(date: Date): boolean {
return !isNaN(date.getTime());
}
export function makeErrorFromAnything<T extends Error>(subject: T): T;
export function makeErrorFromAnything(subject: any): Error;
export function makeErrorFromAnything<T>(subject: T): Error {
return subject instanceof Error
? subject
: new Error(
typeof subject === "symbol" ? subject.toString() : `${subject}`
);
}
export function getMessageFromError(error: Error): string {
if (error instanceof z.ZodError) {
return error.issues
.map(({ path, message }) =>
(path.length ? [path.join("/")] : []).concat(message).join(": ")
)
.join("; ");
}
return error.message;
}
export function getStatusCodeFromError(error: Error): number {
if (error instanceof HttpError) {
return error.statusCode;
}
if (error instanceof z.ZodError) {
return 400;
}
return 500;
}
type Examples<T extends z.ZodTypeAny> = Readonly<z.input<T>[] | z.output<T>[]>;
export const getExamples = <T extends z.ZodTypeAny>(
schema: T,
parseToOutput: boolean
): Examples<T> => {
const examples = getMeta(schema, "examples");
if (examples === undefined) {
return [];
}
return examples.reduce((carry, example) => {
const parsedExample = schema.safeParse(example);
return carry.concat(
parsedExample.success
? parseToOutput
? parsedExample.data
: example
: []
);
}, [] as z.output<typeof schema>[]);
};
export const combinations = <T extends any>(
a: T[],
b: T[]
): { type: "single"; value: T[] } | { type: "tuple"; value: [T, T][] } => {
if (a.length === 0) {
return { type: "single", value: b };
}
if (b.length === 0) {
return { type: "single", value: a };
}
const result: [T, T][] = [];
for (const itemA of a) {
for (const itemB of b) {
result.push([itemA, itemB]);
}
}
return { type: "tuple", value: result };
};
export function getRoutePathParams(path: string): string[] {
const match = path.match(routePathParamsRegex);
if (!match) {
return [];
}
return match.map((param) => param.slice(1));
}
const reduceBool = (arr: boolean[]) =>
arr.reduce((carry, bool) => carry || bool, false);
export function hasTopLevelTransformingEffect(schema: IOSchema): boolean {
if (schema instanceof z.ZodEffects) {
if (schema._def.effect.type !== "refinement") {
return true;
}
}
if (schema instanceof z.ZodUnion) {
return reduceBool(schema.options.map(hasTopLevelTransformingEffect));
}
if (schema instanceof z.ZodIntersection) {
return reduceBool(
[schema._def.left, schema._def.right].map(hasTopLevelTransformingEffect)
);
}
return false; // ZodObject left
}
export function hasUpload(schema: z.ZodTypeAny): boolean {
if (schema instanceof ZodUpload) {
return true;
}
if (schema instanceof z.ZodObject) {
return reduceBool(Object.values<z.ZodTypeAny>(schema.shape).map(hasUpload));
}
if (schema instanceof z.ZodUnion) {
return reduceBool(schema.options.map(hasUpload));
}
if (schema instanceof z.ZodIntersection) {
return reduceBool([schema._def.left, schema._def.right].map(hasUpload));
}
if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {
return hasUpload(schema.unwrap());
}
if (schema instanceof z.ZodEffects || schema instanceof z.ZodTransformer) {
return hasUpload(schema._def.schema);
}
if (schema instanceof z.ZodRecord) {
return hasUpload(schema._def.valueType);
}
if (schema instanceof z.ZodArray) {
return hasUpload(schema._def.type);
}
if (schema instanceof z.ZodDefault) {
return hasUpload(schema._def.innerType);
}
return false;
}
/**
* @desc isNullable() and isOptional() validate the schema's input
* @desc They always return true in case of coercion, which should be taken into account when depicting response
*/
export const hasCoercion = (schema: z.ZodType): boolean =>
"coerce" in schema._def && typeof schema._def.coerce === "boolean"
? schema._def.coerce
: false;
export const tryToTransform = ({
effect,
sample,
}: {
effect: z.Effect<any> & { type: "transform" };
sample: any;
}) => {
try {
return typeof effect.transform(sample, {
addIssue: () => {},
path: [],
});
} catch (e) {
return undefined;
}
};
// obtaining the private helper type from Zod
export type ErrMessage = Exclude<
Parameters<typeof z.ZodString.prototype.email>[0],
undefined
>;
// the copy of the private Zod errorUtil.errToObj
export const errToObj = (message: ErrMessage | undefined) =>
typeof message === "string" ? { message } : message || {};