I'm writing a server in TypeScript, and searching the web I haven't found much about writing a controller that returns an http response using observables. I have a draft and it works, but I wonder whether this is the correct approach especially in the long term, or there are better patterns that I could follow. In My controller I return a promise from a service:
public getUser = (): Promise<User> => {
return this._service.findById('id');
}
The service :
public findById(id: string): Promise<User> {
return this._repo.findById(id).pipe(
map(res => res ? Response.ok(res) : Response.notFound(`id: ${id} not found.`))
).toPromise()
.catch((err: Error) => Response.internalServerError(err));
}
and the repo:
public findById(id: string): Observable<User | null> {
return from(User.findById(id));
}
Once it comes to write longer functions in my service I could create a new observable, do the logic in there and then return the result as a promise. What are your thoughts? Can it be improved? Thanks in advance
Aucun commentaire:
Enregistrer un commentaire