Order
Let's begin by creating a resource for Order.
nest g res domain/ordersWe'll create the basic strucutre for Order, beginning with the enum OrderStatus. Let's do this by creating the file orders/enums/order-status.enum with following content:
export enum OrderStatus {
AWAITING_PAYMENT = 'AWAITING_PAYMENT',
AWAITING_SHIPMENT = 'AWAITING_SHIPMENT',
SHIPPED = 'SHIPPED',
IN_TRANSIT = 'IN_TRANSIT',
COMPLETED = 'COMPLETED',
CANCELED = 'CANCELED',
}We could also use the approach of an immutable array (tuple) and a literal type. This method will be explained in the Extra module 5.
Now, in the order.entity file, define the attributes.
id: number;
status: OrderStatus;
registryDates: RegistryDates;Then, execute the necessary steps to finish assembling the new resource:
In the controller, use the
IdDtowhereveridis being usedRemove the number conversion operator (
+) below each occurrenceUse
PaginationDtoin thefindAll()method (and also in the service)Default page size - 5
Add to the entity the ORM decorators (
@Entity(),@Column(), etc)Register the entity inside the
TypeOrmModulein the resource's own module
However, the enum is not automatically mapped to the database just with the @Column() decorator. We need to explicitly define the enum in its options, like this:
We'll now deal with the matter of relationships. One user may have many orders, and one order belongs to one user. We can see that this is a one-to-many relationship. So, let's begin on the user's side. In the user.entity file, we'll define an attribute for his orders and use the @OneToMany() decorator to map this relationship.
The relationship decorator has two parameters:
The entity on the other side
The name through which this entity is referenced on the other side
Now, let's deal with the order's side, defining the attribute for its customer and using @ManyToOne().
By default, a column representing a foreign key can be null. As an order must always belong to a user, the nullable option is disabled.
Let's now generate and run the migration create-order through the process already known to us.
As a last step, let's make sure that, when a user is searched by id, his orders are also fetched. To do this, go back to the UsersService and, in the findOne() method, alter it like the following:
Notice that now the where clause must be explicitly set.
Commit - Creating order entity, using enum and handling one to many relation
Last updated