# 用 Node.js 构建电商后端

来源：https://docs.nestjs.com/tutorials/ecommerce-backend

使用 NestJS 和 PostgreSQL 在 Node.js 中构建电商后端：商品目录、购物车，以及一套绝不超卖库存的结账流程。

这个商店有员工维护的商品目录、每位顾客各自的购物车，以及一套把购物车变成订单、并且卖出的数量永不超过库存的结账流程。电商后端的大部分内容都是普通的 CRUD。不普通的部分，正是钱和库存易手的地方，所以本教程把时间花在那里：价格用整数分表示，价格冻结进每个订单，库存在检查它的同一条语句中扣减，并且当顾客双击按钮或一千位顾客都想买最后一件商品时，结账依然安全。

完成之后，该 API 将能够：

- 让任何人浏览和搜索商品目录，只让员工创建和编辑商品，这由 [`@nestjs/authorization`](/security/authorization) 实现——它拒绝任何未声明谁可调用的路由。
- 为每位顾客保留一个购物车，按当日价格计价，并显示哪些行当前无法购买。
- 在一个数据库事务中完成结账：取走购物车、取走库存、记录价格，否则什么都不改。
- 让顾客取消尚未发货的订单，取消时把库存放回，并让员工发货。
- 在针对 PostgreSQL 的测试中证明：十位顾客争抢最后一件商品时，恰好只产生一个订单。

它从 [用 JWT 认证构建 REST API](/tutorials/rest-api-jwt-authentication) 的 API 出发——那个 API 用访问令牌和刷新令牌让用户登录，用 Zod 校验请求，并通过 Drizzle 把数据保存在 PostgreSQL 中。本教程不再重复解释这些部分。

以下是各端点，以及添加它们的小节：

| 端点 | 小节 |
| --- | --- |
| `POST /auth/sign-up`、`POST /auth/token`、`POST /auth/token/refresh`、`POST /auth/token/revoke`、`GET /me`、`GET /health/live`、`GET /health/ready` | [从 JWT API 开始](/tutorials/ecommerce-backend#start-from-the-jwt-api) |
| `GET /products`、`GET /products/:id`、`POST /products`、`PATCH /products/:id` | [让员工管理商品目录](/tutorials/ecommerce-backend#let-staff-manage-the-catalog) |
| `GET /cart`、`PUT /cart/items/:productId`、`DELETE /cart/items/:productId` | [维护购物车](/tutorials/ecommerce-backend#keep-a-cart) |
| `POST /orders`、`GET /orders`、`GET /orders/:id` | [结账而不超卖](/tutorials/ecommerce-backend#check-out-without-overselling) |
| `POST /orders/:id/cancel`、`POST /orders/:id/ship` | [取消订单与发货](/tutorials/ecommerce-backend#cancel-and-ship-orders) |

> info **提示** 完成后的应用位于 GitHub：[nestjs/example-ecommerce-backend](https://github.com/nestjs/example-ecommerce-backend)，其中包含测试和 CI 工作流。

#### 从 JWT API 开始

创建项目，并安装本教程用到的全部内容。这些是 JWT 教程用到的包，再加上 `@nestjs/authorization`。`nest new` 还会安装 [NestJS Observe SDK](/observability/sdk)，即 `@nestjs/observe`，并把它接入应用；应用自己的文件则保留它：

```bash
$ npm i -g @nestjs/cli
$ nest new shop-api --minimal
$ cd shop-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/authorization @nestjs/throttler @nestjs/swagger @nestjs/terminus
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite
```

然后从[完成后的 JWT 教程](/tutorials/rest-api-jwt-authentication#sign-users-in-with-jwts)原样取来这些文件：

- `src/config.ts`、`src/main.ts`、`drizzle.config.ts` 和 `vitest.config.e2e.ts`
- `src/auth/`、`src/users/` 和 `src/health/` 下的所有内容
- `test/refresh-token.store.e2e-spec.ts`

略去 `src/notes/` 和 JWT 教程的 `drizzle/` 文件夹：本应用的第一个迁移来自它自己的 schema，就在下一节。在出现名称的地方，把笔记改成商店：`JwtAuth` 中的 `realm`，以及 `main.ts` 中 OpenAPI 文档的标题。把测试脚本加到 `package.json`：

```json
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
```

最后，像 JWT 教程那样，把数据库的 URL 和 `JWT_SECRET` 加到 `.env`，数据库用商店自己的：

```bash
$ docker run -d --name shop-db -e POSTGRES_PASSWORD=shop -e POSTGRES_DB=shop -p 5432:5432 postgres:17
```

它的 URL 写进 `.env`，放在签名密钥旁边：

```bash
DATABASE_URL=postgres://postgres:shop@localhost:5432/shop
# 生成方式：openssl rand -base64 32
JWT_SECRET=
```

顾客和员工使用同一套登录，所以用户现在多了一个角色：

```typescript
@@filename(src/users/user)
export type Role = 'customer' | 'staff';

export interface User {
  id: string;
  email: string;
  role: Role;
  createdAt: Date;
}
```

`UsersRepository` 连同其他列一起返回它：

```typescript
@@filename(src/users/users.repository)
// ...
const columns = { id: users.id, email: users.email, role: users.role, createdAt: users.createdAt };
```

角色不在访问令牌里。`JwtAuth.validate()` 在每个请求上加载用户，因此把某个用户提升为员工、或把他降级，都在他的下一个请求上生效，而不是等到令牌过期。

#### 设计 schema

整个 schema 都放在一个文件里。用户和刷新令牌沿用 JWT 教程的，只加上了角色：

```typescript
@@filename(src/database/schema)
import { sql } from 'drizzle-orm';
import { boolean, check, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  role: text('role', { enum: ['customer', 'staff'] }).notNull().default('customer'),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const products = pgTable(
  'products',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    name: text('name').notNull(),
    description: text('description').notNull(),
    // 金额用整数分表示：不会发生浮点舍入。
    price: integer('price').notNull(),
    stock: integer('stock').notNull(),
    active: boolean('active').notNull().default(true),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [
    check('products_price_positive', sql`${table.price} > 0`),
    // 防止超卖的最后一道防线。
    check('products_stock_not_negative', sql`${table.stock} >= 0`),
  ],
);

export const cartItems = pgTable(
  'cart_items',
  {
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    productId: uuid('product_id')
      .notNull()
      .references(() => products.id, { onDelete: 'cascade' }),
    quantity: integer('quantity').notNull(),
  },
  (table) => [primaryKey({ columns: [table.userId, table.productId] })],
);

export const orders = pgTable(
  'orders',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id),
    status: text('status', { enum: ['placed', 'shipped', 'cancelled'] }).notNull(),
    total: integer('total').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [index('orders_user_id_created_at_idx').on(table.userId, table.createdAt)],
);

// 买了什么，以及按什么价格买的：之后的改价不会改写历史订单。
export const orderItems = pgTable(
  'order_items',
  {
    orderId: uuid('order_id')
      .notNull()
      .references(() => orders.id, { onDelete: 'cascade' }),
    productId: uuid('product_id')
      .notNull()
      .references(() => products.id),
    name: text('name').notNull(),
    unitPrice: integer('unit_price').notNull(),
    quantity: integer('quantity').notNull(),
  },
  (table) => [primaryKey({ columns: [table.orderId, table.productId] })],
);

// @nestjs/authentication 为刷新令牌保存的内容，以其 SHA-256 存储。
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // 族中任一令牌被撤销时，整个族都会被撤销。
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type Product = typeof products.$inferSelect;
export type Order = typeof orders.$inferSelect;
export type OrderItem = typeof orderItems.$inferSelect;
```

- **价格是整数，单位是分。** `19.99` 无法被精确存为浮点数，很多个这样的数相加，总额会漂移。`1999` 可以。
- **订单项复制商品的名称和价格。** 当员工改价或给商品改名时，历史订单保留顾客当时支付的金额。
- **购物车是一张表，以用户和商品为键。** 设置某一行的数量就是一次 upsert，同一个商品不会出现两次。
- **商品是被停用，而不是被删除。** 订单项仍然引用它们。
- **`stock` 不会低于零。** 结账流程从不会这样尝试，但若将来某次改动弄错了，PostgreSQL 会拒绝写入，而不是存下负库存。

生成迁移并应用它（参见[迁移](/data/drizzle#migrations)）：

```bash
$ npx drizzle-kit generate --name=shop
$ npx drizzle-kit migrate
```

#### 让员工管理商品目录

[`@nestjs/authorization`](/security/authorization) 把权限表达为 **策略**（policies），即一些类，其方法回答「这个用户可以做这件事吗？」。把它的模块注册在 `AuthenticationModule` 之后：两者都注册全局守卫，而 authorization 的守卫需要 authentication 设置的用户。加上商店的各个功能模块，根模块是：

```typescript
@@filename(src/app.module)
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { CartModule } from './cart/cart.module.js';
import { HealthModule } from './health/health.module.js';
import { OrdersModule } from './orders/orders.module.js';
import { ProductsModule } from './products/products.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最前面，这样它最后关闭，仍能发送其他模块产生的数据。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前为空：此时 SDK 不发送任何内容。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'shop-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'shop-api',
          audience: 'shop-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    // 放在 AuthenticationModule 之后：它的守卫读取 authentication 设置的用户。
    AuthorizationModule.forRoot(),
    ThrottlerModule.forRoot([
      // 按 IP 地址，作用于每个路由。
      { name: 'default', ttl: minutes(1), limit: 100 },
      // 按邮箱和 IP 地址，作用于请求体指明账号的地方。
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ProductsModule,
    CartModule,
    OrdersModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}
```

- **`ObserveModule` 在 `imports` 中放在第一位**，与 [SDK 的快速开始](/observability/sdk#quick-start) 的做法一致：模块按相反顺序关闭，所以它最后停止，并发送其他模块记录的数据（参见[关闭](/observability/sdk#shutdown)）。来自 JWT 教程的 `main.ts` 把 `ObserveInstrument` 传给 Nest。
- **在关联项目之前，密钥对为空。** 没有密钥对时，SDK 不发送任何内容，并在启动时说明这一点。`npx @nestjs/observe link` 会把 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 写入 `.env`，并把 `--env-file .env` 添加到 `start` 脚本，使这些变量在 `AppModule` 被导入、SDK 读取它们之前就进入环境（参见[从终端关联](/observability/sdk#linking-from-the-terminal)）。

authorization 的守卫 **默认拒绝**：一个路由只有声明了谁可以调用它才会运行——用 `@Can()` 做策略检查，用 `@Can.Anyone()` 表示任何 authentication 放行的调用者，或用 `@Public()`（它等同于 `@Can.Anyone()`）。忘记声明的路由是关闭的，而不是开放的，模块会在启动时为每个这样的路由记一条日志。JWT 教程中 `/auth` 和 `/health` 下的路由已经是 `@Public()`。`GET /me` 面向任何已登录用户：

```typescript
@@filename(src/users/me.controller)
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from './user.js';

@Can.Anyone()
@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: User) {
    return user;
  }
}
```

商品目录的策略只有一个能力：管理商品。user 参数接受 `null`，即访客，这样守卫可以在任何路由上调用它：

```typescript
@@filename(src/products/product.policy)
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';

@Policy()
export class ProductPolicy {
  // `null` 表示访客。
  manage(user: User | null) {
    return user?.role === 'staff';
  }
}
```

请求 schema。价格按整数分校验，所以 `19.99` 会得到 400，而不是变成一个舍入问题：

```typescript
@@filename(src/products/products.schemas)
import { z } from 'zod';

const name = z.string().trim().min(1).max(200);
const description = z.string().max(5_000);
// 单位为分：1999 即 19.99。
const price = z.number().int().positive().max(10_000_000);
const stock = z.number().int().min(0);

export const createProductSchema = z.object({ name, description: description.default(''), price, stock });
export type CreateProductDto = z.infer<typeof createProductSchema>;

export const updateProductSchema = z.object({ name, description, price, stock, active: z.boolean() }).partial();
export type UpdateProductDto = z.infer<typeof updateProductSchema>;

export const listProductsQuerySchema = z.object({
  q: z.string().trim().min(1).max(100).optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  offset: z.coerce.number().int().min(0).default(0),
});
export type ListProductsQuery = z.infer<typeof listProductsQuerySchema>;
```

和 JWT 教程一样，更新 schema 不是用 `partial()` 从创建 schema 派生出来的——那样会保留 `description` 的默认值，进而在每次更新时清空描述。

```typescript
@@filename(src/products/products.service)
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, ilike } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { products, type Product } from '../database/schema.js';
import type { CreateProductDto, ListProductsQuery, UpdateProductDto } from './products.schemas.js';

@Injectable()
export class ProductsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  findAll({ q, limit, offset }: ListProductsQuery): Promise<Product[]> {
    return this.db
      .select()
      .from(products)
      .where(and(eq(products.active, true), q ? ilike(products.name, `%${escapeLike(q)}%`) : undefined))
      .orderBy(asc(products.name), asc(products.id))
      .limit(limit)
      .offset(offset);
  }

  async findOne(id: string): Promise<Product> {
    const [product] = await this.db
      .select()
      .from(products)
      .where(and(eq(products.id, id), eq(products.active, true)));
    return product ?? notFound();
  }

  async create(dto: CreateProductDto): Promise<Product> {
    const [product] = await this.db.insert(products).values(dto).returning();
    return product;
  }

  async update(id: string, dto: UpdateProductDto): Promise<Product> {
    const [product] = await this.db.update(products).set(dto).where(eq(products.id, id)).returning();
    return product ?? notFound();
  }
}

function notFound(): never {
  throw new NotFoundException('Product not found');
}

/** 搜索中的 `%` 和 `_` 是字面字符，不是通配符。 */
const escapeLike = (value: string) => value.replace(/[\\%_]/g, (char) => `\\${char}`);
```

搜索走 Drizzle 的 `ilike()`，它把模式作为参数发送，因此无法注入 SQL。转义 `%` 和 `_` 可避免搜索 `100%` 时匹配到所有内容。

读路由是 `@Public()`，写路由在处理器运行之前检查策略。访客会得到 401，也就是要求他登录；已登录的顾客会得到 403，也就是告诉他登录也没用：

```typescript
@@filename(src/products/products.controller)
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { ApiSecurity } from '@nestjs/swagger';
import { z } from 'zod';
import { ProductPolicy } from './product.policy.js';
import {
  createProductSchema,
  listProductsQuerySchema,
  updateProductSchema,
  type CreateProductDto,
  type ListProductsQuery,
  type UpdateProductDto,
} from './products.schemas.js';
import { ProductsService } from './products.service.js';

const productId = { schema: z.uuid() };

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Public()
  @ApiSecurity({})
  @Get()
  findAll(@Query({ schema: listProductsQuerySchema }) query: ListProductsQuery) {
    return this.productsService.findAll(query);
  }

  @Public()
  @ApiSecurity({})
  @Get(':id')
  findOne(@Param('id', productId) id: string) {
    return this.productsService.findOne(id);
  }

  @Can(ProductPolicy, 'manage')
  @Post()
  create(@Body({ schema: createProductSchema }) dto: CreateProductDto) {
    return this.productsService.create(dto);
  }

  @Can(ProductPolicy, 'manage')
  @Patch(':id')
  update(@Param('id', productId) id: string, @Body({ schema: updateProductSchema }) dto: UpdateProductDto) {
    return this.productsService.update(id, dto);
  }
}
```

`@Can()` 会针对策略做类型检查，所以拼错能力名无法通过编译。把策略注册为其模块的提供者；authorization 模块会到那里找到它：

```typescript
@@filename(src/products/products.module)
import { Module } from '@nestjs/common';
import { ProductPolicy } from './product.policy.js';
import { ProductsController } from './products.controller.js';
import { ProductsService } from './products.service.js';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService, ProductPolicy],
})
export class ProductsModule {}
```

注册接口创建的是顾客账号。请在数据库里提升第一位员工（此后可以交给自己的管理界面来做）：

```bash
$ docker exec shop-db psql -U postgres -d shop -c "UPDATE users SET role = 'staff' WHERE email = 'sam@example.com'"
```

#### 维护购物车

购物车的一行由一个商品和一个数量组成。设置数量是对该表主键的 upsert，所以重复请求之后购物车保持不变：

```typescript
@@filename(src/cart/cart.schemas)
import { z } from 'zod';

export const setQuantitySchema = z.object({
  quantity: z.number().int().min(1).max(100),
});
export type SetQuantityDto = z.infer<typeof setQuantitySchema>;
```

服务按当日价格读取购物车，并用这一次 upsert 写入一行：

```typescript
@@filename(src/cart/cart.service)
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { cartItems, products } from '../database/schema.js';

export interface CartLine {
  productId: string;
  name: string;
  unitPrice: number;
  quantity: number;
  /** 结账当前能否取走这一行。 */
  available: boolean;
}

export interface Cart {
  items: CartLine[];
  /** 单位为分，按当日价格计算。 */
  total: number;
}

@Injectable()
export class CartService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  async get(userId: string): Promise<Cart> {
    const rows = await this.db
      .select({
        productId: cartItems.productId,
        name: products.name,
        unitPrice: products.price,
        quantity: cartItems.quantity,
        active: products.active,
        stock: products.stock,
      })
      .from(cartItems)
      .innerJoin(products, eq(products.id, cartItems.productId))
      .where(eq(cartItems.userId, userId))
      .orderBy(asc(products.name));
    const items = rows.map(({ active, stock, ...line }) => ({ ...line, available: active && stock >= line.quantity }));
    const total = items.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0);
    return { items, total };
  }

  async setQuantity(userId: string, productId: string, quantity: number): Promise<Cart> {
    const [product] = await this.db
      .select({ id: products.id })
      .from(products)
      .where(and(eq(products.id, productId), eq(products.active, true)));
    if (!product) {
      throw new NotFoundException('Product not found');
    }
    // 这里不预留库存：结账会在取走库存的同一条语句中检查它。
    await this.db
      .insert(cartItems)
      .values({ userId, productId, quantity })
      .onConflictDoUpdate({ target: [cartItems.userId, cartItems.productId], set: { quantity } });
    return this.get(userId);
  }

  async remove(userId: string, productId: string): Promise<Cart> {
    await this.db.delete(cartItems).where(and(eq(cartItems.userId, userId), eq(cartItems.productId, productId)));
    return this.get(userId);
  }
}
```

购物车不预留库存。若在顾客添加商品时就预留，被遗弃的购物车就能占住全部库存；购物车对当前买不了的行显示 `available: false`，而库存真正被取走的地方是结账。购物车按当日价格计价，订单则按结账那一刻的价格计价。

每个已登录用户都有一个购物车，所以控制器声明 `@Can.Anyone()`，并且每个查询都按令牌中的用户限定范围：

```typescript
@@filename(src/cart/cart.controller)
import { Body, Controller, Delete, Get, Param, Put } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { setQuantitySchema, type SetQuantityDto } from './cart.schemas.js';
import { CartService } from './cart.service.js';

const productId = { schema: z.uuid() };

// 每位已登录顾客都有自己的购物车，并且只能看到自己的。
@Can.Anyone()
@Controller('cart')
export class CartController {
  constructor(private readonly cartService: CartService) {}

  @Get()
  get(@CurrentUser('id') userId: string) {
    return this.cartService.get(userId);
  }

  @Put('items/:productId')
  setQuantity(
    @CurrentUser('id') userId: string,
    @Param('productId', productId) id: string,
    @Body({ schema: setQuantitySchema }) { quantity }: SetQuantityDto,
  ) {
    return this.cartService.setQuantity(userId, id, quantity);
  }

  @Delete('items/:productId')
  remove(@CurrentUser('id') userId: string, @Param('productId', productId) id: string) {
    return this.cartService.remove(userId, id);
  }
}
```

购物车模块注册控制器和服务：

```typescript
@@filename(src/cart/cart.module)
import { Module } from '@nestjs/common';
import { CartController } from './cart.controller.js';
import { CartService } from './cart.service.js';

@Module({
  controllers: [CartController],
  providers: [CartService],
})
export class CartModule {}
```

#### 结账而不超卖

结账正是电商后端通常出错的地方。最直白的写法是读取商品、检查 `stock` 是否足够，再写入新的库存。两位顾客在同一时刻结账，都读到库存为 1，都通过检查，于是都拿到了最后一件商品的订单。本教程末尾的测试让十位这样的顾客同时访问 PostgreSQL：那种写法在每一次运行中都为这一件商品接受了好几个订单。

下面的结账在一个事务内、用条件语句取走它需要的一切：

```typescript
@@filename(src/orders/orders.service)
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, desc, eq, gte, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { cartItems, orderItems, orders, products, type Order, type OrderItem } from '../database/schema.js';

export type OrderWithItems = Order & { items: Omit<OrderItem, 'orderId'>[] };

@Injectable()
export class OrdersService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** 把用户的购物车变成订单，或者抛出异常且不做任何改动。 */
  checkout(userId: string): Promise<OrderWithItems> {
    return this.db.transaction(async (tx) => {
      // 取走购物车是第一条语句。对同一购物车的第二次结账
      // 会等待这个事务，然后发现购物车已空。
      const taken = await tx.delete(cartItems).where(eq(cartItems.userId, userId)).returning();
      if (taken.length === 0) {
        throw new ConflictException('Your cart is empty');
      }
      // 让所有结账按同一顺序锁住商品，这样两者永远不会死锁。
      taken.sort((a, b) => a.productId.localeCompare(b.productId));

      const items: Omit<OrderItem, 'orderId'>[] = [];
      for (const { productId, quantity } of taken) {
        // 在一条语句中检查并取走库存：不存在先读后写的窗口。
        const [product] = await tx
          .update(products)
          .set({ stock: sql`${products.stock} - ${quantity}` })
          .where(and(eq(products.id, productId), eq(products.active, true), gte(products.stock, quantity)))
          .returning({ name: products.name, price: products.price });
        if (!product) {
          // 回滚整个事务：购物车和其他商品都不受影响。
          throw new ConflictException(`Not enough stock for product ${productId}`);
        }
        items.push({ productId, name: product.name, unitPrice: product.price, quantity });
      }

      const total = items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0);
      const [order] = await tx.insert(orders).values({ userId, status: 'placed', total }).returning();
      await tx.insert(orderItems).values(items.map((item) => ({ ...item, orderId: order.id })));
      return { ...order, items };
    });
  }

  // findMine()、findOne()、cancel() 和 ship() 在下一节给出。
}
```

- **库存由一条 `UPDATE` 检查和扣减**，它的 `WHERE` 子句要求库存足够。PostgreSQL 在更新某一行的同时锁住该行，所以第二个结账的 `UPDATE` 会等待第一个事务，然后看到它留下的库存。库存不够时，这条语句不改任何行、不返回任何内容，结账随即抛出异常。
- **抛出异常会回滚一切。** 来自 [Drizzle](/data/drizzle#drizzle-transactions) 的 `transaction()` 在回调抛出异常时回滚，因此在第三个商品上失败的结账会让前两个商品的库存和整个购物车保持原样。Nest 把 `ConflictException` 变成 409。
- **购物车是用 `DELETE ... RETURNING` 先取走的。** 这正是双击结账依然安全的原因：第二个请求的 `DELETE` 要等第一个事务在同一批行上的锁，而一旦第一个事务提交，它就发现购物车已空，于是返回 409。一次点击，一个订单，无需管理幂等键。
- **所有结账都按同一顺序锁定商品。** 两个购物车都含同样的两个商品、却按相反顺序取走时，各自持有其中一行、等待对方那一行，PostgreSQL 会以死锁为由中止其中一个。按商品 id 排序杜绝了这种情况。
- **价格来自那条 `UPDATE` 的 `RETURNING`**，所以订单记录的是取走库存那一刻的价格，而不是购物车早些时候显示的价格。
- **每个查询都走 `tx`。** 换成在注入的数据库上查询，就会在该连接池的另一条连接上、在事务之外执行。

#### 取消订单与发货

订单从 `placed` 出发，或由顾客改为 `cancelled`，或由员工改为 `shipped`。两者都是针对当前状态的条件更新，所以当顾客取消的同时员工发货时，恰好只有一方成功，另一方得到 409。取消还会在同一个事务里把库存放回。`OrdersService` 的其余部分：

```typescript
@@filename(src/orders/orders.service)
  findMine(userId: string): Promise<Order[]> {
    return this.db.select().from(orders).where(eq(orders.userId, userId)).orderBy(desc(orders.createdAt)).limit(100);
  }

  async findOne(userId: string, id: string): Promise<OrderWithItems> {
    const [order] = await this.db
      .select()
      .from(orders)
      .where(and(eq(orders.id, id), eq(orders.userId, userId)));
    if (!order) {
      throw new NotFoundException('Order not found');
    }
    return { ...order, items: await this.items(this.db, order.id) };
  }

  /** 所有者取消一个尚未发货的订单，其库存会被放回。 */
  cancel(userId: string, id: string): Promise<Order> {
    return this.db.transaction(async (tx) => {
      // 条件更新：取消和发货争抢同一订单时，只有一方成功。
      const [order] = await tx
        .update(orders)
        .set({ status: 'cancelled' })
        .where(and(eq(orders.id, id), eq(orders.userId, userId), eq(orders.status, 'placed')))
        .returning();
      if (!order) {
        return this.refuse(tx, id, userId);
      }
      for (const { productId, quantity } of await this.items(tx, order.id)) {
        await tx
          .update(products)
          .set({ stock: sql`${products.stock} + ${quantity}` })
          .where(eq(products.id, productId));
      }
      return order;
    });
  }

  /** 员工把已下单的订单标记为已发货。 */
  async ship(id: string): Promise<Order> {
    const [order] = await this.db
      .update(orders)
      .set({ status: 'shipped' })
      .where(and(eq(orders.id, id), eq(orders.status, 'placed')))
      .returning();
    return order ?? this.refuse(this.db, id);
  }

  private items(db: Pick<NodePgDatabase, 'select'>, orderId: string) {
    return db
      .select({
        productId: orderItems.productId,
        name: orderItems.name,
        unitPrice: orderItems.unitPrice,
        quantity: orderItems.quantity,
      })
      .from(orderItems)
      .where(eq(orderItems.orderId, orderId))
      .orderBy(asc(orderItems.name));
  }

  /** 条件更新为何什么都没改：订单不存在（或不属于他）时返回 404，否则返回 409。 */
  private async refuse(db: Pick<NodePgDatabase, 'select'>, id: string, userId?: string): Promise<never> {
    const [order] = await db
      .select({ status: orders.status })
      .from(orders)
      .where(and(eq(orders.id, id), userId ? eq(orders.userId, userId) : undefined));
    if (!order) {
      throw new NotFoundException('Order not found');
    }
    throw new ConflictException(`Order is already ${order.status}`);
  }
}
```

别人的订单会得到 404，和订单不存在时一样。发货需要第二个策略：

```typescript
@@filename(src/orders/order.policy)
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';

@Policy()
export class OrderPolicy {
  ship(user: User | null) {
    return user?.role === 'staff';
  }
}
```

控制器在发货路由上检查这个策略。其余路由面向任何已登录顾客，其查询都限定在该顾客范围内：

```typescript
@@filename(src/orders/orders.controller)
import { Controller, Get, HttpCode, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { OrderPolicy } from './order.policy.js';
import { OrdersService } from './orders.service.js';

const orderId = { schema: z.uuid() };

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  // 结账：购物车变成订单。
  @Can.Anyone()
  @Post()
  checkout(@CurrentUser('id') userId: string) {
    return this.ordersService.checkout(userId);
  }

  @Can.Anyone()
  @Get()
  findMine(@CurrentUser('id') userId: string) {
    return this.ordersService.findMine(userId);
  }

  @Can.Anyone()
  @Get(':id')
  findOne(@CurrentUser('id') userId: string, @Param('id', orderId) id: string) {
    return this.ordersService.findOne(userId, id);
  }

  @Can.Anyone()
  @Post(':id/cancel')
  @HttpCode(200)
  cancel(@CurrentUser('id') userId: string, @Param('id', orderId) id: string) {
    return this.ordersService.cancel(userId, id);
  }

  @Can(OrderPolicy, 'ship')
  @Post(':id/ship')
  @HttpCode(200)
  ship(@Param('id', orderId) id: string) {
    return this.ordersService.ship(id);
  }
}
```

`POST /orders` 创建订单，返回 201。取消和发货修改的是已有订单，因此返回 200。

```typescript
@@filename(src/orders/orders.module)
import { Module } from '@nestjs/common';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';

@Module({
  controllers: [OrdersController],
  providers: [OrdersService, OrderPolicy],
})
export class OrdersModule {}
```

#### 试一试

启动应用：

```bash
$ npm run start:dev
```

注册一位顾客和一位员工，并按上面的说明提升该员工。提升之后他们的令牌仍然有效，因为角色是在每个请求上读取的（这里及以下的令牌和响应体都做了截断）：

```bash
$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ SAM="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
```

只有员工能添加商品：

```bash
$ curl localhost:3000/products -H "$ADA" --json '{"name":"Mechanical keyboard","price":12900,"stock":5}'
{"message":"Forbidden","statusCode":403}
$ curl localhost:3000/products -H "$SAM" --json '{"name":"Mechanical keyboard","description":"Hot-swappable switches","price":12900,"stock":5}'
{"id":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","description":"Hot-swappable switches","price":12900,"stock":5,"active":true,"createdAt":"2026-11-19T20:04:12.673Z"}
$ curl localhost:3000/products -H "$SAM" --json '{"name":"Wrist rest","price":19.99,"stock":1}'
{"message":["price: Invalid input: expected int, received number"],"error":"Bad Request","statusCode":400}
```

填写购物车并结账（腕托以同样的方式加入，价格为 1999 分）：

```bash
$ curl -X PUT localhost:3000/cart/items/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$ADA" --json '{"quantity":2}'
{"items":[{"productId":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","unitPrice":12900,"quantity":2,"available":true}],"total":25800}
$ curl -X POST localhost:3000/orders -H "$ADA"
{"id":"02ebc117-957f-4566-a2bb-e343afb01854","userId":"ed17ba4e-4d43-4aa4-9116-c6eda67ec2a7","status":"placed","total":27799,"createdAt":"2026-11-19T20:04:25.979Z","items":[{"productId":"afffc03b-...","name":"Mechanical keyboard","unitPrice":12900,"quantity":2},{"productId":"dc51c8f1-...","name":"Wrist rest","unitPrice":1999,"quantity":1}]}
$ curl -X POST localhost:3000/orders -H "$ADA"
{"message":"Your cart is empty","error":"Conflict","statusCode":409}
```

还剩三个键盘。要四个的购物车无法结账，并保留它那一行：

```bash
$ curl -X PUT localhost:3000/cart/items/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$ADA" --json '{"quantity":4}'
$ curl -X POST localhost:3000/orders -H "$ADA"
{"message":"Not enough stock for product afffc03b-9142-4761-be96-84e6da07f8d4","error":"Conflict","statusCode":409}
$ curl localhost:3000/cart -H "$ADA"
{"items":[{"productId":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","unitPrice":12900,"quantity":4,"available":false}],"total":51600}
```

员工提高价格。订单保留它下单时的价格。取消订单会把库存放回，而且订单只能被取消一次：

```bash
$ curl -X PATCH localhost:3000/products/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$SAM" --json '{"price":14900}'
$ curl localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854 -H "$ADA"
{"id":"02ebc117-...","status":"placed","total":27799,...,"items":[{"productId":"afffc03b-...","name":"Mechanical keyboard","unitPrice":12900,"quantity":2},...]}
$ curl -X POST localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854/cancel -H "$ADA"
{"id":"02ebc117-957f-4566-a2bb-e343afb01854","userId":"ed17ba4e-4d43-4aa4-9116-c6eda67ec2a7","status":"cancelled","total":27799,"createdAt":"2026-11-19T20:04:25.979Z"}
$ curl -X POST localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854/cancel -H "$ADA"
{"message":"Order is already cancelled","error":"Conflict","statusCode":409}
```

顾客不能发货（403），员工不能给已取消的订单发货（409），而另一位顾客访问该订单会得到 404。

#### 测试它

这里真正重要的保证都与并发有关，而 PGlite 这类进程内数据库只有一条连接，请求永远不会真正竞争。所以这些测试针对真实的 PostgreSQL 服务器、通过连接池运行，并用 `app.inject()` 发送同时执行的请求。请为测试单独建一个数据库，因为这些测试会清空这些表：

```typescript
@@filename(test/checkout.e2e-spec)
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { products, users } from '../src/database/schema.js';
import type { Role } from '../src/users/user.js';

// 带连接池的真实 PostgreSQL，让并发的结账真正竞争。
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('Shop API (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  let app: NestNodeApplication;

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, products, refresh_tokens CASCADE`);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // 默认成本下的 scrypt 每次哈希占用 128 MiB、耗时几百毫秒。
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await app.init();
  });

  afterAll(() => app.close()); // 同时关闭连接池

  let clients = 0;

  /** 注册用户，并返回以该用户身份认证的请求头。 */
  async function signUp(email: string, role: Role = 'customer') {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      // 每个用户都从自己的地址注册，就像在生产环境中那样：
      // 注册是按 IP 地址限流的。
      remoteAddress: `10.0.0.${++clients}`,
    });
    await db.update(users).set({ role }).where(eq(users.email, email));
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  async function createProduct(stock: number) {
    const res = await app.inject({
      method: 'POST',
      url: '/products',
      headers: await signUp(`staff-${crypto.randomUUID()}@example.com`, 'staff'),
      payload: { name: 'Limited edition keycaps', price: 9900, stock },
    });
    expect(res.statusCode).toBe(201);
    return res.json<{ id: string }>().id;
  }

  it('lets only staff edit the catalog', async () => {
    const payload = { name: 'Desk mat', price: 2500, stock: 10 };
    const customer = await signUp('customer@example.com');
    expect((await app.inject({ method: 'POST', url: '/products', payload })).statusCode).toBe(401);
    expect((await app.inject({ method: 'POST', url: '/products', headers: customer, payload })).statusCode).toBe(403);
  });

  it('sells the last unit exactly once', async () => {
    const productId = await createProduct(1);
    const buyers = await Promise.all(Array.from({ length: 10 }, (_, i) => signUp(`buyer${i}@example.com`)));
    for (const headers of buyers) {
      await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 1 } });
    }

    const results = await Promise.all(buyers.map((headers) => app.inject({ method: 'POST', url: '/orders', headers })));

    expect(results.map((res) => res.statusCode).sort()).toEqual([201, ...Array(9).fill(409)]);
    const [{ stock }] = await db.select({ stock: products.stock }).from(products).where(eq(products.id, productId));
    expect(stock).toBe(0);
  });

  it('places one order when the same cart is checked out twice at once', async () => {
    const productId = await createProduct(10);
    const headers = await signUp('double-click@example.com');
    await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 2 } });

    const results = await Promise.all([1, 2].map(() => app.inject({ method: 'POST', url: '/orders', headers })));

    expect(results.map((res) => res.statusCode).sort()).toEqual([201, 409]);
    const orders = await app.inject({ method: 'GET', url: '/orders', headers });
    expect(orders.json()).toHaveLength(1);
  });

  it('puts the stock back when an order is cancelled', async () => {
    const productId = await createProduct(3);
    const headers = await signUp('cancel@example.com');
    await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 3 } });
    const order = (await app.inject({ method: 'POST', url: '/orders', headers })).json<{ id: string }>();

    const cancelled = await app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers });
    expect(cancelled.json()).toMatchObject({ status: 'cancelled' });
    const product = await app.inject({ method: 'GET', url: `/products/${productId}` });
    expect(product.json()).toMatchObject({ stock: 3 });
    expect((await app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers })).statusCode).toBe(409);
  });
});
```

先创建一次测试数据库，然后运行整个测试套件：

```bash
$ docker exec shop-db psql -U postgres -c "CREATE DATABASE shop_test"
$ TEST_DATABASE_URL=postgres://postgres:shop@localhost:5432/shop_test npm run test:e2e

 Test Files  1 passed (1)
      Tests  4 passed (4)
```

把 `checkout()` 中的库存 `UPDATE` 换成一次读取、一次 JavaScript 检查和一次写入，那么「最后一件商品恰好只卖一次」就会失败：十位顾客中有好几位都拿到了订单。

JWT 教程的[刷新令牌存储测试](/tutorials/rest-api-jwt-authentication#test-it)在这里原样适用。两个测试文件都会清空同一个数据库中的表，所以要依次运行它们，并加上 `npm run test:e2e -- --no-file-parallelism`。

#### 生产环境检查清单

JWT 教程[检查清单](/tutorials/rest-api-jwt-authentication#production-checklist)中的每一项都适用。具体到这个商店：

- **按结账的需求设定连接池大小。** 每次结账在整个事务期间占用一条连接，热门商品的结账还会在其行锁上排队。请让事务保持短小：`checkout()` 中除了数据库不等待任何东西，并且应当一直如此。在事务之前或之后调用支付服务商，绝不要在事务内调用。
- **用幂等键收款。** 结账可以安全重试，因为第一次之后购物车就没了。支付不是这样：重试一次扣款就扣两次钱。服务商的 API 接受一个键；把订单的 id 发过去。要让自己写的支付端点可以安全重试，参见[幂等键](/reliability/idempotency)。
- **绝不要相信客户端传来的价格。** 订单的价格在结账那一刻取自 `products` 表。在这里，客户端发送的价格或总额在结构上就会被忽略；添加折扣时请保持这一点。
- **继续停用商品，而不是删除商品。** 订单项会引用它们。
- **为生产环境准备独立的 Observe 密钥对**，从项目的 **API Keys** 页面获取，作为 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 放入平台的环境：`start:prod` 不会加载 `.env`。然后观察结账：热门商品上的锁等待会表现为结账变慢，而不是错误。[NestJS Observe](/observability/overview) 记录每个请求及其 span 追踪（包括 SQL 语句）和每个路由的 p95 延迟，因此促销期间变慢的结账在顾客抱怨之前就能看见。
- **为员工账号加上第二因素。** 员工的令牌可以改写商品目录的价格。参见[添加双因素认证](/security/authentication#add-two-factor-authentication)，并在员工路由上用 `@Authenticate()` 强制要求它。

#### 下一步

- 接收支付，并通过服务商的 webhook 把订单标记为已支付：[用 webhook 接收支付](/tutorials/payments-webhooks)。
- 在请求之外发送订单确认：[邮件](/application/mail) 和 [队列](/application/queues)。若只想在订单的事务提交之后发送事件，请使用[事务性发件箱](/reliability/outbox)。
- 让顾客看到按订单划分的权限，或给员工更细的角色：[授权](/security/authorization)。
- 在生产环境逐个请求地观察缓慢的结账和锁等待：[可观测性](/observability/overview)。
