'Delay an async method after the NestJS controller method response finish
I have a @Get() method in a Controller. I get the response, but after the response is successfully I would like to call an async method after a delay of some milliseconds.
I'm using a Middleware, but seems like the response is pending for the time specified in the async method.
How can I do to solve the response in time, and after the delay call the custom method from the Custom Service?
Here is the used sample code:
@Controller()
export class CustomController {
@Get("custom-controller-route")
getCustomValue(@Res() response: Response) {
return response.status(200).send({
value: 1
})
}
}
The middleware code is the following:
@Injectable()
export class CustomMiddleware implements NestMiddleware {
constructor(private readonly customService: CustomService) {}
use(req: any, res: any, next: () => void) {
let send = res.send
res.send = async (customResponse: CustomResponse) => {
const { value } = customResponse
await customService.customMethod(value, 5000) // Delay of 5 seconds
res.send = send
return res.send(exchangeRateResponse)
}
next()
}
}
And the CustomService has the next code:
@Injectable()
export class CustomService {
async customMethod(value: any, delay) {
await firstValueFrom(
timer(delay).pipe(
tap(() => {
// Here is the logic that needs to be run in the delay time after the response is finished
console.log(`Custom Service - custom method called with: ${value} after: ${delay} milliseconds.`)
})
)
)
}
}
Solution 1:[1]
I could do it instead of returning the response in the Controller method, I only call the res.status(200).send({}) with the specific response and after that I call the specific method call with the delay.
@Controller()
export class CustomController {
@Get("custom-controller-route")
getCustomValue(@Res() response: Response) {
response.status(200).send({ value: 1 })
// Call the delayed Service method
}
}
Any other better option is welcome
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | frankfullstack |
