handle delete resrved word (#3078)

This commit is contained in:
Fred K. Schott 2022-04-12 19:57:05 -07:00 committed by GitHub
parent 1bfdf43dca
commit d33e177817
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 5 deletions

View file

@ -0,0 +1,5 @@
---
'astro': minor
---
Support the "del" API method, because "delete" is a reserved word.

View file

@ -0,0 +1,5 @@
---
'astro': minor
---
Add support for an "all" API method, to handle all requests

View file

@ -441,17 +441,32 @@ export function defineScriptVars(vars: Record<any, any>) {
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);
}