Return a function to be executed - Typescript

Asked

Viewed 210 times

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!!

1 answer

0

You can use the pattern .then() .catch() of the Promises Encapsulate the name that comes in the parameter and returns a new promisse, then you don’t even need the callbacks. It’s a little fuzzy on these code snippets but I think it’s about that.

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);
    }
}
public async runAsyncFunction(asyncFunction: Promise<any>) {
    const pr = new Promise((resolve, reject)=>{
        try {
            const data = await asyncFunction;
            resolve(data)
        } catch (error) {
            reject(error)
        }
    })

    return pr
}

Ai on your controller does something like this

const userInfoResponse = await this.asyncHandler.runAsyncFunction(this.idmService.getToken(access_token))
            .then(data=>console.log('sucesso'))
            .catch(erro=>this.responseHandler.unauthorizedResponse(res, modelResposta,'mensagem de erro'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.