You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.3 KiB
50 lines
1.3 KiB
import log4js from "logger";
|
|
|
|
interface IConfig {
|
|
|
|
}
|
|
|
|
const defaultConfig: IConfig = {
|
|
|
|
}
|
|
|
|
const logger = log4js.getLogger("ERROR");
|
|
|
|
function assertRequiredContext(
|
|
event: { context: Record<string, unknown> },
|
|
keys: string[],
|
|
) {
|
|
for (const key of keys) {
|
|
if (!event.context[key]) {
|
|
throw new Error(`event.context.${key} is not initialized`);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D>(
|
|
handlerOrConfig?: EventHandler<T, D> | IConfig,
|
|
_handler?: EventHandler<T, D>,
|
|
): EventHandler<T, D> => {
|
|
const handler = typeof handlerOrConfig === 'function' ? handlerOrConfig : _handler;
|
|
if (!handler) {
|
|
throw new Error('handler or config is required');
|
|
}
|
|
Object.assign({ ...defaultConfig }, typeof handlerOrConfig === 'object' ? handlerOrConfig : {});
|
|
|
|
return defineEventHandler<T>(async (event) => {
|
|
try {
|
|
assertRequiredContext(event, ["auth", "config"]);
|
|
const response = await handler(event)
|
|
return response
|
|
} catch (error) {
|
|
logger.error(
|
|
event?.method ?? "",
|
|
event?.path ?? "(no request)",
|
|
`[request]`,
|
|
"\n",
|
|
error
|
|
);
|
|
throw error
|
|
}
|
|
})
|
|
}
|