-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
server.ts
172 lines (156 loc) · 4.98 KB
/
server.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
import { z } from 'zod';
import { getApiContext } from '../store.js';
import { type MaybePromise, hasContentType } from '../utils.js';
import {
ActionError,
ActionInputError,
type ErrorInferenceObject,
type SafeResult,
callSafely,
} from './shared.js';
export * from './shared.js';
export { z } from 'zod';
export { getApiContext } from '../store.js';
export type Accept = 'form' | 'json';
export type InputSchema<T extends Accept> = T extends 'form'
? z.AnyZodObject | z.ZodType<FormData>
: z.ZodType;
type Handler<TInputSchema, TOutput> = TInputSchema extends z.ZodType
? (input: z.infer<TInputSchema>) => MaybePromise<TOutput>
: (input?: any) => MaybePromise<TOutput>;
export type ActionClient<
TOutput,
TAccept extends Accept,
TInputSchema extends InputSchema<TAccept> | undefined,
> = TInputSchema extends z.ZodType
? ((
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>
) => Promise<Awaited<TOutput>>) & {
safe: (
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>
) => Promise<
SafeResult<
z.input<TInputSchema> extends ErrorInferenceObject
? z.input<TInputSchema>
: ErrorInferenceObject,
Awaited<TOutput>
>
>;
}
: ((input?: any) => Promise<Awaited<TOutput>>) & {
safe: (input?: any) => Promise<SafeResult<never, Awaited<TOutput>>>;
};
export function defineAction<
TOutput,
TAccept extends Accept = 'json',
TInputSchema extends InputSchema<Accept> | undefined = TAccept extends 'form'
? // If `input` is omitted, default to `FormData` for forms and `any` for JSON.
z.ZodType<FormData>
: undefined,
>({
accept,
input: inputSchema,
handler,
}: {
input?: TInputSchema;
accept?: TAccept;
handler: Handler<TInputSchema, TOutput>;
}): ActionClient<TOutput, TAccept, TInputSchema> {
const serverHandler =
accept === 'form'
? getFormServerHandler(handler, inputSchema)
: getJsonServerHandler(handler, inputSchema);
Object.assign(serverHandler, {
safe: async (unparsedInput: unknown) => {
return callSafely(() => serverHandler(unparsedInput));
},
});
return serverHandler as ActionClient<TOutput, TAccept, TInputSchema>;
}
function getFormServerHandler<TOutput, TInputSchema extends InputSchema<'form'>>(
handler: Handler<TInputSchema, TOutput>,
inputSchema?: TInputSchema
) {
return async (unparsedInput: unknown): Promise<Awaited<TOutput>> => {
if (!(unparsedInput instanceof FormData)) {
throw new ActionError({
code: 'UNSUPPORTED_MEDIA_TYPE',
message: 'This action only accepts FormData.',
});
}
if (!(inputSchema instanceof z.ZodObject)) return await handler(unparsedInput);
const parsed = await inputSchema.safeParseAsync(formDataToObject(unparsedInput, inputSchema));
if (!parsed.success) {
throw new ActionInputError(parsed.error.issues);
}
return await handler(parsed.data);
};
}
function getJsonServerHandler<TOutput, TInputSchema extends InputSchema<'json'>>(
handler: Handler<TInputSchema, TOutput>,
inputSchema?: TInputSchema
) {
return async (unparsedInput: unknown): Promise<Awaited<TOutput>> => {
const context = getApiContext();
const contentType = context.request.headers.get('content-type');
if (!contentType || !hasContentType(contentType, ['application/json'])) {
throw new ActionError({
code: 'UNSUPPORTED_MEDIA_TYPE',
message: 'This action only accepts JSON.',
});
}
if (!inputSchema) return await handler(unparsedInput);
const parsed = await inputSchema.safeParseAsync(unparsedInput);
if (!parsed.success) {
throw new ActionInputError(parsed.error.issues);
}
return await handler(parsed.data);
};
}
/** Transform form data to an object based on a Zod schema. */
export function formDataToObject<T extends z.AnyZodObject>(
formData: FormData,
schema: T
): Record<string, unknown> {
const obj: Record<string, unknown> = {};
for (const [key, baseValidator] of Object.entries(schema.shape)) {
let validator = baseValidator;
if (baseValidator instanceof z.ZodOptional || baseValidator instanceof z.ZodNullable) {
validator = baseValidator._def.innerType;
}
if (validator instanceof z.ZodBoolean) {
obj[key] = formData.has(key);
} else if (validator instanceof z.ZodArray) {
obj[key] = handleFormDataGetAll(key, formData, validator);
} else {
obj[key] = handleFormDataGet(key, formData, validator, baseValidator);
}
}
return obj;
}
function handleFormDataGetAll(
key: string,
formData: FormData,
validator: z.ZodArray<z.ZodUnknown>
) {
const entries = Array.from(formData.getAll(key));
const elementValidator = validator._def.type;
if (elementValidator instanceof z.ZodNumber) {
return entries.map(Number);
} else if (elementValidator instanceof z.ZodBoolean) {
return entries.map(Boolean);
}
return entries;
}
function handleFormDataGet(
key: string,
formData: FormData,
validator: unknown,
baseValidator: unknown
) {
const value = formData.get(key);
if (!value) {
return baseValidator instanceof z.ZodOptional ? undefined : null;
}
return validator instanceof z.ZodNumber ? Number(value) : value;
}