I have this repository , it should get the message by id :
findOne(id: number) {
return readFile('messages.json', 'utf8', (err, file: string) => {
const messages = JSON.parse(file);
return messages[id];
});
}
this is the service :
findOne(id: number) {
return this.messagesRepo.findOne(id);
}
and this is the controller
@Get('/:id')
getMessage(@Param() param: GetMessageDTO) {
const message = this.messagesService.findOne(param.id);
if (message == null) {
throw new NotFoundException('message not found');
}
return message;
}
I want the controller to wait for the execution of the function but I can't use async/await because readFile doesn't return promise , what should I do?
CodePudding user response:
instead of readFile
from fs
, you can use the one from promises API of FS module like so:
import { readFile } from 'fs/promises'
// ...
async findOne(id: number): Promise<any> {
const jsonFileTxtBuffer = await readFile('messages.json');
const messages = JSON.parse(jsonFileTxtBuffer);
return messages[id];
}
Don't forget the await
on calling .findOne()
, of course.
pretty basic JS and node.js stuff not related with NestJS :)