diff --git a/.changeset/chilly-terms-smoke.md b/.changeset/chilly-terms-smoke.md new file mode 100644 index 000000000..1a390c310 --- /dev/null +++ b/.changeset/chilly-terms-smoke.md @@ -0,0 +1,5 @@ +--- +'astro': minor +--- + +Support the "del" API method, because "delete" is a reserved word. diff --git a/.changeset/lazy-kangaroos-rush.md b/.changeset/lazy-kangaroos-rush.md new file mode 100644 index 000000000..c759b968b --- /dev/null +++ b/.changeset/lazy-kangaroos-rush.md @@ -0,0 +1,5 @@ +--- +'astro': minor +--- + +Add support for an "all" API method, to handle all requests diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index 749591248..067468497 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -441,17 +441,32 @@ export function defineScriptVars(vars: Record) { return markHTMLString(output); } -// Renders an endpoint request to completion, returning the body. -export async function renderEndpoint(mod: EndpointHandler, request: Request, params: Params) { - const chosenMethod = request.method?.toLowerCase() ?? 'get'; - const handler = mod[chosenMethod]; +function getHandlerFromModule(mod: EndpointHandler, method: string) { + // If there was an exact match on `method`, return that function. + if (mod[method]) { + return mod[method]; + } + // Handle `del` instead of `delete`, since `delete` is a reserved word in JS. + if (method === 'delete' && mod['del']) { + return mod['del']; + } + // If a single `all` handler was used, return that function. + if (mod['all']) { + return mod['all']; + } + // Otherwise, no handler found. + return undefined; +} +/** Renders an endpoint request to completion, returning the body. */ +export async function renderEndpoint(mod: EndpointHandler, request: Request, params: Params) { + const chosenMethod = request.method?.toLowerCase(); + const handler = getHandlerFromModule(mod, chosenMethod); if (!handler || typeof handler !== 'function') { throw new Error( `Endpoint handler not found! Expected an exported function for "${chosenMethod}"` ); } - return await handler.call(mod, params, request); }