3
I’m in a situation where I would like to generate an engine that runs an async function and that runs a successful callback on Ry and a catch error, and the responsibility of these callbacks is to send a res.send() on Express.
Motor code:
public async runAsyncFunction(asyncFunction: Promise<any>,
errorCallback: () => Response,
successCallback?: (any) => Response) {
try {
const data = await asyncFunction;
if (!successCallback) {
return data;
}
return successCallback(data);
} catch (error) {
return errorCallback();
}
}
Code functions of Callback
export class ResponseHandler {
public successResponse(responseModel: any, res: Response) {
return () => res.status(statusCode.success_ok).send(responseModel);
}
public unauthorizedResponse(res: Response, responseModel: ResponseModel, errorMessage: string) {
responseModel.message = errorMessage;
return () => res.status(statusCode.client_error_unauthorized).send(responseModel);
}
}
Invocation in the controller
const userInfoResponse = await this.asyncHandler.runAsyncFunction(this.idmService.getToken(access_token),
this.responseHandler.unauthorizedResponse(res, modelResposta,
'mensagem de erro'));
The error I’m getting is as follows:
Error: Can't set headers after they are sent.
Thanks!!