Order

Let's begin by creating a resource for Order.

nest g res domain/orders

We'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',
}

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 IdDto wherever id is being used

  • Remove the number conversion operator (+) below each occurrence

  • Use PaginationDto in the findAll() 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 TypeOrmModule in 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

{ type: 'enum', enum: OrderStatus, default: OrderStatus.AWAITING_PAYMENT }

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.

@OneToMany(() => Order, (order) => order.customer)
orders: Order[];

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().

@ManyToOne(() => User, (customer) => customer.orders, { nullable: false })
customer: User;

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

const user = await this.usersRepository.findOne({
  where: { id },
  relations: {
    orders: true,
  },
});

Notice that now the where clause must be explicitly set.

Commit - Creating order entity, using enum and handling one to many relation

Last updated