mirror of
https://github.com/directus/directus.git
synced 2026-01-24 00:38:12 -05:00
Reduce overengineering on async-handler (#15340)
This commit is contained in:
19
api/src/utils/async-handler.test.ts
Normal file
19
api/src/utils/async-handler.test.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { RequestHandler, NextFunction, Request, Response } from 'express';
|
||||
import '../../src/types/express.d.ts';
|
||||
import asyncHandler from './async-handler';
|
||||
|
||||
let mockRequest: Partial<Request & { token?: string }>;
|
||||
let mockResponse: Partial<Response>;
|
||||
const nextFunction: NextFunction = jest.fn();
|
||||
|
||||
test('Wraps async middleware in Promise resolve that will catch rejects and pass them to the nextFn', async () => {
|
||||
const err = new Error('testing');
|
||||
|
||||
const middleware: RequestHandler = async (req, res, next) => {
|
||||
throw err;
|
||||
};
|
||||
|
||||
await asyncHandler(middleware)(mockRequest as Request, mockResponse as Response, nextFunction as NextFunction);
|
||||
|
||||
expect(nextFunction).toHaveBeenCalledWith(err);
|
||||
});
|
||||
@@ -1,22 +1,6 @@
|
||||
import { ErrorRequestHandler, RequestHandler } from 'express';
|
||||
import type { RequestHandler, Request, Response, NextFunction } from 'express';
|
||||
|
||||
/**
|
||||
* Handles promises in routes.
|
||||
*/
|
||||
function asyncHandler(handler: RequestHandler): RequestHandler;
|
||||
function asyncHandler(handler: ErrorRequestHandler): ErrorRequestHandler;
|
||||
function asyncHandler(handler: RequestHandler | ErrorRequestHandler): RequestHandler | ErrorRequestHandler {
|
||||
if (handler.length === 2 || handler.length === 3) {
|
||||
const scoped: RequestHandler = (req, res, next) =>
|
||||
Promise.resolve((handler as RequestHandler)(req, res, next)).catch(next);
|
||||
return scoped;
|
||||
} else if (handler.length === 4) {
|
||||
const scoped: ErrorRequestHandler = (err, req, res, next) =>
|
||||
Promise.resolve((handler as ErrorRequestHandler)(err, req, res, next)).catch(next);
|
||||
return scoped;
|
||||
} else {
|
||||
throw new Error(`Failed to asyncHandle() function "${handler.name}"`);
|
||||
}
|
||||
}
|
||||
const asyncHandler = (fn: RequestHandler) => (req: Request, res: Response, next: NextFunction) =>
|
||||
Promise.resolve(fn(req, res, next)).catch(next);
|
||||
|
||||
export default asyncHandler;
|
||||
|
||||
Reference in New Issue
Block a user