Order

Before defining the Order model, let's first create the OrderStatus enum.

enum OrderStatus {
  AWAITING_PAYMENT
  AWAITING_SHIPMENT
  SHIPPED
  IN_TRANSIT
  COMPLETED
  CANCELED
}

And then, create the model.

model Order {
  id Int @id @default(autoincrement())

  status OrderStatus @default(AWAITING_PAYMENT)

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Now, about the relations. A user may have many orders, and an order belongs to one user. It is a one-to-many relation. Let's begin at the user side.

orders Order[]

Then, the order side. Note that the foreign key definition must be separate.

customer   User @relation(fields: [customerId], references: [id])
customerId Int

Let's now generate and run the migration through the process already known to us.

yarn migrate:create create-order
yarn migrate:run

We'll then create the orders resource.

nest g res domain/orders

And perform the steps to finish its assembly

  • Exclude the entities folder

  • 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

In the UsersService, in the findOne() method, let's also fetch its orders, by adding include after the where clause.

include: {
  orders: true
}

Commit - Creating order model

Last updated