Order
Now it's time for the order logic. In the CreateDTO, we'll need to start from scratch. To create an order, a payload must be received with a customer
and the order's items
. We already know that the customer
can be represented by the IdDto
, but what about the items
? How do we represent a single item
?
An orderItem
will be represented by its own DTO, containing the product
and quantity
. The price
won't be present as we should not allow any possibility of arbitrary prices being sent, don't you think? It's safer to search for it directly in the database.
Let's then begin by creating it in orders -> dto -> order-item.dto with following content. We can see that, using everything we learned so far, our validation is becoming elegant and consistent.
Then, we should also create an identifier for the OrderItemDto
. Note that we check if product
exists before accessing it.
This may even be encapsulated into an object of constants that contains all the identifier functions, and they should follow the signature of ArrayUniqueIdentifier
to be compliant with the @ArrayUnique()
validator. After that, also adjust accordingly in the CreateProductDto
.
We can now conclude our CreateOrderDto
.
Here, we're not obliged to use @IsDefined()
because @ArrayNotEmpty()
already enforces that the field should be an array, and not empty.
An order cannot be changed once created. Because of that, we can delete the UpdateDTO file, along with the update()
method in both the controller and service.
Going now into the service, we can copy the product's structure, as it will be pretty similar. An order
will be fetched together with its items
and their respective products
, along with its customer
and payment
. Therefore, we can already add these relations to the findAll()
and findOne()
methods.
We must now write an auxiliary method that will receive the orderItemDto
and will then find its product
's price
in the database to then return an orderItem
with a price
. Let's do so at the bottom of the service.
Remember to inject a Repository
for OrderItem
and Product
, and also register them inside the TypeOrmModule
in the OrdersModule
.
Finally, the create()
method will be written. We shall transform all the items
that came to also have a price
. We'll do this with the help of Promise.all()
as all the searches can be done in parallel, which is more performant. At last, the order
is saved.
Due to the cascade
option we set earlier, we are saving in the database both the order
and its items
.
Commit - Implementing order logic and saving with cascade
Last updated