in src/common/providers/https.ts [833:877]
export function onDispatchHandler<Req = any>(
handler: v1TaskHandler | v2TaskHandler<Req>
): (req: Request, res: express.Response) => Promise<void> {
return async (req: Request, res: express.Response): Promise<void> => {
try {
if (!isValidRequest(req)) {
logger.error('Invalid request, unable to process.');
throw new HttpsError('invalid-argument', 'Bad Request');
}
const context: TaskContext = {};
const status = await checkAuthToken(req, context);
// Note: this should never happen since task queue functions are guarded by IAM.
if (status === 'INVALID') {
throw new HttpsError('unauthenticated', 'Unauthenticated');
}
const data: Req = decode(req.body.data);
if (handler.length === 2) {
await handler(data, context);
} else {
const arg: TaskRequest<Req> = {
...context,
data,
};
// For some reason the type system isn't picking up that the handler
// is a one argument function.
await (handler as any)(arg);
}
res.status(204).end();
} catch (err) {
if (!(err instanceof HttpsError)) {
// This doesn't count as an 'explicit' error.
logger.error('Unhandled error', err);
err = new HttpsError('internal', 'INTERNAL');
}
const { status } = err.httpErrorCode;
const body = { error: err.toJSON() };
res.status(status).send(body);
}
};
}