Controller routes

Finishing the file-related routes in the products controller.

Great, let's now concentrate on the remaining routes in the ProductsController, and after that start implementing the logic in the ProductsService.

Well, the uploadImages() route is almost done, we just need to extract the id of the entity.

@Param() { id }: IdDto,

And call the service's method, yet to be created.

return this.productsService.uploadImages(id, files);

Now, the downloadImage() route. However, a new problem arises. In this route, two path params will be used: the id of the product and the filename of the image. When using DTOs to validate path params, only a single DTO can be used, as was explained previously. Then, how to solve this matter?

First, we'll create a very simple DTO for the filename in files -> dto -> filename.dto.

export class FilenameDto {
  @IsString()
  readonly filename: string;
}

We have the two necessary DTOs. Now, let's combine them into a single DTO. We can achieve that with the IntersectionType. Then, in the same place, let's also create the file id-filename.dto, where we'll have a DTO that is the combination of both.

export class IdFilenameDto extends IntersectionType(IdDto, FilenameDto) {}

Remember to import the mapped-types from swagger from now on.

Perfect, let's now return to the ProductsController and add the route to download an image.

@Get(':id/images/:filename')
downloadImage(@Param() { id, filename }: IdFilenameDto) {
  return this.productsService.downloadImage(id, filename);
}

And finally, the route to delete an image.

@Delete(':id/images/:filename')
deleteImage(@Param() { id, filename }: IdFilenameDto) {
  return this.productsService.deleteImage(id, filename);
}

As a last step, let's consider that the routes uploadImages() and deleteImage() should only be accessible to a manager, and that the route downloadImage() is public.

With this, we have finished the routes in the controller. Let's then go to the service in order to implement these methods.

Commit - Finishing file related routes in controller

Last updated