Cleaner routes with NestJs

Returning newly created items

{
"firstName": "Murphy",
"lastName": "Eddie"
}
{
"id": 378,
"firstName": "Murphy",
"lastName": "Eddie"
}
async create(user: User): Promise<User> {
return await this.userRepository.save(user);
}
@Post()
async create(@Body() user: CreateUserDto): Promise<User> {
return await this.userService.create(user);
}

Returning updated content

  • save the received item in the database and then return it
  • save the item, fetch it from the database to finally return the fetched item
await this.service.update(id, user);
return user;
return await this.service.update(id, user);

Wrong identifier

  • the connection broke during saving; our application didn’t handle the error correctly and believe our user is saved
  • with shared resources among different user: one delete it, while the other doesn’t know it got deleted
  • offline cache did not synchronize with remote API: the user called API from its phone got items in cache; then log onto from its laptop remove it; later get back to his phone then try to update it (item still in cache)
async delete(id: any): Promise<User> {
let user = await this.findById(id)
if (user == null) {
throw new HttpException(
`invalid id: ${id}`,
HttpStatus.NOT_FOUND
);
}
await this.userRepository.delete(user);
return user;
}
async update(id: any, user: User): Promise<User> {
// trying to update a user with an invalid id ?
if (await this.findById(id) == null) {
throw new HttpException(
`invalid id: ${id}`,
HttpStatus.NOT_FOUND,
);
}
await this.userRepository.update(id, user);
return await this.findById(id);
}
private async findById(id: number): Promise<User> {
return await this.userRepository.findOne({
where: [{ id: id }],
});
}

POST /UpdateOrCreate endpoint

return await this.service.update(id, user);
async updateOrCreate(id: any, user: User): Promise<User> {
await this.userRepository.update(id, user);
return await this.findById(id);
}

Farewell

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
lsmod

lsmod

Self-taught programmer; passionate about Rust & Blockchains