Skip to content

Commit

Permalink
feat: add explicit accept property
Browse files Browse the repository at this point in the history
  • Loading branch information
bholmesdev committed Apr 26, 2024
1 parent d00cfb0 commit 0621116
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
12 changes: 7 additions & 5 deletions packages/astro/src/actions/runtime/virtual/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ export * from './shared.js';
export { z } from '../../../../zod.mjs';

export function defineAction<TOutput, TInputSchema extends z.ZodType>({
accept,
input: inputSchema,
handler,
}: {
input?: TInputSchema;
accept: 'json' | 'form' | 'all';
handler: (input: z.infer<TInputSchema>, context: APIContext) => MaybePromise<TOutput>;
}): (input: z.input<TInputSchema> | FormData) => Promise<Awaited<TOutput>> {
return async (unparsedInput): Promise<Awaited<TOutput>> => {
Expand All @@ -21,14 +23,14 @@ export function defineAction<TOutput, TInputSchema extends z.ZodType>({
if (!inputSchema) return await handler(unparsedInput, context);

if (unparsedInput instanceof FormData) {
if (!(inputSchema instanceof z.ZodObject)) {
if (accept === 'json') {
throw new ActionError({
status: 'INTERNAL_SERVER_ERROR',
message:
'`input` must use a Zod object schema with z.object() when accepting form data.',
status: 'UNSUPPORTED_MEDIA_TYPE',
message: 'This action only accepts JSON input. To accept form data, set the `accept` option to either `form` or `all`.'
});
}
unparsedInput = upgradeFormData(unparsedInput, inputSchema);
// TODO: form input schema narrowing
unparsedInput = upgradeFormData(unparsedInput, inputSchema as any);
}

const parsed = inputSchema.safeParse(unparsedInput);
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/actions/runtime/virtual/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ type ActionErrorStatus =
| 'UNAUTHORIZED'
| 'FORBIDDEN'
| 'NOT_FOUND'
| 'UNSUPPORTED_MEDIA_TYPE'
| 'INTERNAL_SERVER_ERROR';

export class ActionError extends Error {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export default {
blog: {
like: defineAction({
input: z.object({ postId: z.string() }),
accept: 'json',
handler: async ({ postId }, context) => {
await new Promise((r) => setTimeout(r, 200));

Expand All @@ -23,6 +24,7 @@ export default {
}),

comment: defineAction({
accept: 'all',
input: z.object({
postId: z.string(),
author: z.string(),
Expand Down

0 comments on commit 0621116

Please sign in to comment.