Skip to content

4. 第 3 章 - [RdvMedecins] 应用的 [NestJS] 服务器

本章逐个文件详细介绍本文档附带的 [rdvmedecins-nestjs-server] 文件夹的内容。它沿用本课程一贯的格式:先给出逐行编号的源代码,然后是标题为“我们来解读这段代码”的部分,解释需要进一步说明的行。每个项目文件夹还包含自己的 README.md 文件,其中有这些说明的精简版。

4.1. 数据库

[dbrdvmedecins] 数据库的结构与原文档(2014 年,Spring 4 / [MySQL] 5)相同:相同的表——[doctors], [clients], [slots], [appointments]——相同的外键,以及相同的唯一性约束。唯一的新增内容是由本次移植的“身份验证”步骤引入的:表 [users]。

4.1.1. [database/dbrdvmedecins.sql]

  -- =========================================================================
  -- Database [dbrdvmedecins] - MySQL 8
  --
  -- This script reproduces EXACTLY the relational schema of the original document
  -- (2014, Spring 4 / Spring Data / MySQL 5): same tables, same columns,
  -- same foreign keys, same uniqueness constraint. Only the database engine
  -- changes its name (MySQL 5 -> MySQL 8), not the structure.
  --
  -- The [users] table now appears ("authentication" step of this
 -- port). The original document used THREE tables (users, roles,
 -- users_roles) to allow a user to have SEVERAL roles.
 -- Since this application only knows two mutually exclusive roles
 -- (ADMIN, USER), we simplify here to a single [role] column
 -- on the [users] table rather than rebuilding the original many-to-
 -- many relation - a deliberate teaching simplification, documented
 -- in the "Authentication" chapter of the course.
 -- =========================================================================

 -- we start again from an empty database on each run of the script (handy in development)
 DROP TABLE IF EXISTS appointments;
 DROP TABLE IF EXISTS slots;
 DROP TABLE IF EXISTS clients;
 DROP TABLE IF EXISTS doctors;
 DROP TABLE IF EXISTS users;

 CREATE DATABASE IF NOT EXISTS dbrdvmedecins CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
 USE dbrdvmedecins;

 CREATE TABLE doctors (
   id         INT AUTO_INCREMENT PRIMARY KEY,
   version    INT NOT NULL DEFAULT 0,
   title      VARCHAR(5)  NOT NULL,
   last_name  VARCHAR(20) NOT NULL,
   first_name VARCHAR(20) NOT NULL
 );

 CREATE TABLE clients (
   id         INT AUTO_INCREMENT PRIMARY KEY,
   version    INT NOT NULL DEFAULT 0,
   title      VARCHAR(5)  NOT NULL,
   last_name  VARCHAR(20) NOT NULL,
   first_name VARCHAR(20) NOT NULL
 );

 CREATE TABLE slots (
   id           INT AUTO_INCREMENT PRIMARY KEY,
   version      INT NOT NULL DEFAULT 0,
   doctor_id    INT NOT NULL,
   start_hour   INT NOT NULL,
   start_minute INT NOT NULL,
   end_hour     INT NOT NULL,
   end_minute   INT NOT NULL,
   CONSTRAINT fk_slots_doctor FOREIGN KEY (doctor_id) REFERENCES doctors(id)
 );

 CREATE TABLE appointments (
   id         INT AUTO_INCREMENT PRIMARY KEY,
   version    INT NOT NULL DEFAULT 0,
   day        DATE NOT NULL,
   slot_id    INT NOT NULL,
   client_id  INT NOT NULL,
   CONSTRAINT fk_appointments_slot   FOREIGN KEY (slot_id)   REFERENCES slots(id),
   CONSTRAINT fk_appointments_client FOREIGN KEY (client_id) REFERENCES clients(id),
   CONSTRAINT unq1_appointments UNIQUE (day, slot_id)
 );

 CREATE TABLE users (
   id       INT AUTO_INCREMENT PRIMARY KEY,
   version  INT NOT NULL DEFAULT 0,
   login    VARCHAR(30) NOT NULL UNIQUE,
   password VARCHAR(100) NOT NULL,
   name     VARCHAR(40) NOT NULL,
   role     VARCHAR(10) NOT NULL
 );

 INSERT INTO doctors (title, last_name, first_name) VALUES
   ('Mme', 'PELISSIER', 'Marie'), ('Mr', 'TATOU', 'Paul'), ('Melle','DUPONT', 'Sophie');

 INSERT INTO clients (title, last_name, first_name) VALUES
   ('Mr', 'MARTIN', 'Jean'), ('Mme', 'DURAND', 'Alice'),
   ('Melle','BISTROU', 'Brigitte'), ('Mr', 'GERMAN', 'Luc');

 INSERT INTO slots (doctor_id, start_hour, start_minute, end_hour, end_minute) VALUES
   (1, 8, 0, 8, 20), (1, 8, 20, 8, 40), /* ... */ (1, 11, 40, 12, 0);

 INSERT INTO slots (doctor_id, start_hour, start_minute, end_hour, end_minute) VALUES
   (2, 14, 0, 14, 20), (2, 14, 20, 14, 40), /* ... */ (2, 17, 40, 18, 0);

 INSERT INTO appointments (day, slot_id, client_id) VALUES (CURDATE(), 2, 3);

 INSERT INTO users (login, password, name, role) VALUES
   ('admin', '$2b$10$YSNBJXXHX9mp13nPZb6YGu8M1jR6uvPwO1s2X73z0QAqBR7TOQjoq', 'Administrator', 'ADMIN'),
   ('user',  '$2b$10$6Cvoion7AgJkpYHw5N0jMuWPf8T90J28En56kWBL9PT0bXt7lwW7.', 'User',          'USER');

我们来解读这段代码:

  • 第 20–24 行:[DROP TABLE IF EXISTS …] ——脚本每次执行都从空数据库开始,并按依赖关系的相反顺序删除(先是引用 `[slots]` 和 `clients` 的 `appointments`,一直到不被任何表引用的 `users`):[MySQL] 会拒绝删除仍被外键引用的表;
  • 第 48 行:[doctor_id INT NOT NULL],然后是第 53 行:[CONSTRAINT fk_slots_doctor FOREIGN KEY …] ——时间段始终属于某位医生;
  • 第 64 行:[CONSTRAINT unq1_appointments UNIQUE (day, slot_id)] ——应用的核心业务规则:同一天的同一个时间段只能被预约一次。防止重复预约的正是这个约束,而且仅靠这个约束——验证器和业务逻辑层都不会显式地再次检查它(见下文的 addAppointment);
  • 第 67–74 行:[CREATE TABLE users (…)] ——本步骤新增的表。`login` 是 UNIQUE 的(两个用户不能使用相同的登录 ID);`password` 存储的是使用 bcrypt 哈希后的密码(绝不存明文);role 取值为 'ADMIN' 或 'USER'——一个简单的文本列,而原文档使用三张表(users、roles、users_roles)来允许每个用户拥有多个角色。由于本应用只需要两个互斥的角色,原来的多对多关系就显得多余了;
  • 第 91–93 行:[INSERT INTO users …] ——两个演示账户,admin/admin(角色 ADMIN)和 user/user(角色 USER),其密码已用 bcrypt 哈希(加盐 10 轮)——绝不存明文,在这个演示脚本中也是如此。

4.2. 分层组织

服务器遵循原项目的分层结构:

Image

每一层只与紧邻其右侧的层通信,即 [5-8]:因此,例如控制器 [5] 绝不会直接与 [7] 层通信。这遵循与原 Spring 项目相同的设计原则,并使每一层都可以独立于其他层被替换。

4.3. [TypeORM] 实体(src/entities/)

实体 是把数据库表的行表示为 TypeScript 对象的类——直接对应原项目中的 JPA 实体(包 rdvmedecins.entities)。

4.3.1. src/entities/abstract.entity.ts

Image

1
2
3
4
5
6
7
8
9
  import { [PrimaryGeneratedColumn], [VersionColumn] } from 'typeorm';

  export abstract class AbstractEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @VersionColumn()
    version: number;
  }

我们来解读这段代码:

  • 第 4 行:[@PrimaryGeneratedColumn()] ——声明由 DBMS 自动递增的主键——完全等价于 JPA 中的 @Id + @GeneratedValue(strategy = GenerationType.AUTO);
  • 第 7 行:[@VersionColumn()] ——[TypeORM] 用于 乐观锁的原生机制:[TypeORM] 在每次修改时自动递增该列,如果您尝试保存的实体其版本与数据库中的版本不再一致(其间有人修改过它),就会抛出错误——完全等价于 JPA/Hibernate 中的 @Version;
  • 第 3 行:[export abstract class AbstractEntity {] ——这个类没有用 [@Entity] 装饰:它本身不对应任何表。[TypeORM] 把这种技术称为“具体表继承”(Concrete Table Inheritance):每个用 [@Entity] 装饰的子类都有自己的表,包含所有继承的列——完全等价于 JPA 中的 @MappedSuperclass。

4.3.2. src/entities/person.entity.ts

  import { [Column] } from 'typeorm';
  import { AbstractEntity } from './abstract.entity';

  export abstract class Person extends AbstractEntity {
    @Column({ length: 5 })
    title: string;

    @Column({ name: 'last_name', length: 20 })
    lastName: string;

   @Column({ name: 'first_name', length: 20 })
   firstName: string;
 }

我们来解读这段代码:

  • 第 4 行:[export abstract class Person extends AbstractEntity {] ——把医生和患者共有的字段(称谓、姓、名)归在一起,同时继承 id/version([AbstractEntity])。与其父类一样,它也没有用 [@Entity] 装饰:它是([TypeORM])版本的,对应原项目中的类 [Personne]——后者同样是 @MappedSuperclass;
  • 第 5、8、11 行:[@Column({ length: N })] / [@Column({ name: '...', length: N })] ——三个定长文本列(后两个带有显式的蛇形命名列名 last_name / first_name),相当于 JPA 中的 [@Column](length = N) private String ...。

4.3.3. src/entities/doctor.entity.ts

1
2
3
4
5
6
7
8
9
  import { [Entity], [OneToMany] } from 'typeorm';
  import { Person } from './person.entity';
  import { Slot } from './slot.entity';

  @Entity({ name: 'doctors' })
  export class Doctor extends Person {
    @OneToMany(() => Slot, (slot) => slot.doctor)
    slots: Slot[];
  }

我们来解读这段代码:

  • 第 5 行:[@Entity({ name: 'doctors' })] ——将该类声明为 [TypeORM] 实体,持久化到表 [doctors]中——完全等价于 JPA 中的 [@Entity] + @Table(name = "[doctors]");
  • 第 6 行:[export class Doctor extends Person {] ——继承 title/lastName/firstName(来自 [Person])以及 id/version(来自 [AbstractEntity]),无需重新声明;
  • 第 7 行:[@OneToMany(() => Slot, (slot) => slot.doctor)] ——声明反向关系“一位医生有多个时间段”:这是一个便于导航的功能,原项目中没有 (原项目只在另一个方向上声明,即在 [Creneau] 一侧),但用 TypeORM 很容易添加。

4.3.4. src/entities/client.entity.ts

1
2
3
4
5
  import { [Entity] } from 'typeorm';
  import { Person } from './person.entity';

  @Entity({ name: 'clients' })
  export class Client extends Person {}

我们来解读这段代码:

  • 第 4–5 行:[@Entity({ name: 'clients' }) export class Client extends Person {}] ——与 [Doctor] 的原理完全相同,没有额外的关系:一张表 [clients],包含从 Person 继承的相同三列。词汇提醒:[Client] 在这里指医疗诊所的 患者 (原业务领域的词汇),不要与“HTTP 客户端”混淆。

4.3.5. src/entities/slot.entity.ts

  import { [Column], [Entity], [JoinColumn], [ManyToOne], [RelationId] } from 'typeorm';
  import { AbstractEntity } from './abstract.entity';
  import { Doctor } from './doctor.entity';

  @Entity({ name: 'slots' })
  export class Slot extends AbstractEntity {
    @Column({ name: 'start_hour' }) startHour: number;
    @Column({ name: 'start_minute' }) startMinute: number;
    @Column({ name: 'end_hour' }) endHour: number;
   @Column({ name: 'end_minute' }) endMinute: number;

   @ManyToOne(() => Doctor, (doctor) => doctor.slots)
   @JoinColumn({ name: 'doctor_id' })
   doctor: Doctor;

   @RelationId((slot: Slot) => slot.doctor)
   doctorId: number;
 }

我们来解读这段代码:

  • 第 7–10 行:[@Column({ name: 'start_hour' }) startHour: number; …] ——预约时间段的四个时间边界(开始和结束的小时/分钟),四个单独的整数,各自映射到其蛇形命名的列(start_hour、start_minute、end_hour、end_minute);
  • 第 12 行:[@ManyToOne(() => Doctor, (doctor) => doctor.slots)] ——多个时间段属于同一位医生。默认情况下,[TypeORM] 读取时间段时不会加载“doctor”关系(默认的“懒加载”行为):必须显式请求(在查询中使用选项 relations: ['doctor'])——正如在 JPA 方面,FetchType.LAZY 要求在 JPQL 查询中显式使用 `left join fetch` 才能获取医生;
  • 第 13 行:[@JoinColumn({ name: 'doctor_id' })] ——指定表 [slots] 中外键列的名称;
  • 第 16 行:[@RelationId((slot: Slot) => slot.doctor)] ——在 [TypeORM] 方面,与原项目中只读字段 idMedecin([@Column](name = "id_medecin", insertable = false, updatable = false))完全对应且符合惯用法:它直接公开外键的值,无需加载整个 [Doctor] 实体——这对构建轻量的 JSON 响应很有用(见下文的 Web 层)。

注:[@RelationId] 字段是一个 虚拟列,由 [TypeORM] 事后计算得出——它不是真正的 SQL 列,不能用于“查询构建器”的 WHERE 子句(见下文的 [SlotRepository])。它仅用于在实体加载后 获取 外键的值。

4.3.6. src/entities/appointment.entity.ts

  import { [Column], [Entity], [JoinColumn], [ManyToOne], [RelationId], [Unique] } from 'typeorm';
  import { AbstractEntity } from './abstract.entity';
  import { Client } from './client.entity';
  import { Slot } from './slot.entity';

  @Entity({ name: 'appointments' })
  @Unique('unq1_appointments', ['day', 'slot'])
  export class Appointment extends AbstractEntity {
    @Column({ type: 'date' })
   day: string;

   @ManyToOne(() => Client)
   @JoinColumn({ name: 'client_id' })
   client: Client;

   @ManyToOne(() => Slot)
   @JoinColumn({ name: 'slot_id' })
   slot: Slot;

   @RelationId((appointment: Appointment) => appointment.client)
   clientId: number;

   @RelationId((appointment: Appointment) => appointment.slot)
   slotId: number;
 }

我们来解读这段代码:

  • 第 7 行:[@Unique('unq1_appointments', ['day', 'slot'])] ——在 [TypeORM] 一侧,对应数据库脚本中的 SQL 约束。注意:这里引用的是关系名(“slot”),而不是字段 [@RelationId] (“slotId”)——后者是虚拟列,[TypeORM] 不接受把它用在 @Unique 约束中。[TypeORM] 会自行把 'slot' 映射到其实际的外键列(slot_id);
  • 第 9 行:[@Column({ type: 'date' })] ——类型为 'date'(而非 'datetime'):只保留日期,不保留时间——与 JPA 方面指定的 TemporalType.DATE 完全一致;
  • 第 12–18 行:[@ManyToOne(...) / @JoinColumn(...)] ——两个关系,分别指向 [Client] 和 [Slot],原理与 [slot.entity.ts] 相同;
  • 第 20–24 行:[@RelationId(...)] ——对应原项目中 idClient/idCreneau 字段的只读等价物(机制与 Slot.doctorId 相同,见上文)。

4.3.7. src/entities/user.entity.ts

  import { [Column], [Entity] } from 'typeorm';
  import { AbstractEntity } from './abstract.entity';

  export type Role = 'ADMIN' | 'USER';

  @Entity({ name: 'users' })
  export class User extends AbstractEntity {
    @Column()
    login: string;

   @Column()
   password: string;

   @Column()
   name: string;

   @Column()
   role: Role;
 }

我们来解读这段代码:

  • 第 4 行:[export type Role = ‘ADMIN’ | ‘USER’;] ——TypeScript 中两个字符串的简单联合:应用管理的仅有的两个角色。这个类型在处理角色的所有其他地方都被复用(roles.decorator.ts、jwt.strategy.ts、[React] 客户端……);
  • 第 6 行:[@Entity({ name: 'users' })] ——与其他实体一样,对应一张专用的表;
  • 第 12 行:[password: string;] ——存储 哈希后的 (bcrypt)密码,绝不存明文——见 auth.service.ts;
  • 第 18 行:[role: Role;] ——单个列,而不是原 Spring 项目中的多对多关系(users/roles/users_roles)。本应用只识别两个互斥的角色(用户要么是 ADMIN 要么是 USER,绝不会两者兼有):重建原来的关系只会增加复杂性而没有任何实际好处。这是出于教学目的有意做的简化,就像本章前面遇到的枚举 `[ResponseStatus]` 一样。

4.4. 业务对象(src/domain/)

Image

这些类不对应任何数据库表:它们是通过组合多个实体即时构造出来的,用来表示应用中有用的概念(“Pelissier 医生 2026 年 9 月 13 日的日程”),但不需要按原样存储。相当于原项目中同名的“domain”子文件夹(或包)。

4.4.1. src/domain/doctor-day-slot.ts

1
2
3
4
5
6
7
8
9
  import { [Slot] } from '[../entities/slot.entity]';
  import { Appointment } from '../entities/appointment.entity';

  export class DoctorDaySlot {
    constructor(
      public slot: Slot,
      public appointment: Appointment | null, // 如果该时间段当天空闲,则为 null
    ) {}
  }

我们来解读这段代码:

  • 第 4 行:[export class DoctorDaySlot {] ——把一个时间段与给定日期在该时间段内可能已安排的预约关联起来;
  • 第 5–8 行:[constructor(public slot: Slot, public appointment: Appointment | null) {}] ——在构造函数参数中直接使用语法 [public] 是 TypeScript 的一种简写:它各用一行同时声明并初始化这两个属性,无需另外编写 [this.slot = slot] 。当时间段可预约时,[appointment] 为 null。

4.4.2. src/domain/doctor-day-schedule.ts

  import { [Doctor] } from '[../entities/doctor.entity]';
  import { DoctorDaySlot } from './doctor-day-slot';

  export class DoctorDaySchedule {
    constructor(
      public doctor: Doctor,
      public day: string, // 格式为 "yyyy-MM-dd"
      public doctorDaySlots: DoctorDaySlot[],
    ) {}
 }

我们来解读这段代码:

  • 第 4 行:[export class DoctorDaySchedule {] ——某位医生在给定日期的完整日程:相关医生、日期,以及其时间段列表(每个时间段标记为可预约或已预约;见上文的 [DoctorDaySlot] );
  • 第 8 行:[public doctorDaySlots: DoctorDaySlot[],] ——由 [BusinessService.getDoctorDaySchedule] 计算得出(见下文);控制器把这个列表转换为 JSON 返回给 [React] 客户端。

4.5. DAO 层(src/repositories/)

DAO 层(数据访问对象,Data Access Object)是项目中唯一直接与 TypeORM/MySQL 通信的部分——相当于原项目中的 Spring Data 接口(包 rdvmedecins.repositories)。

Image

Spring Data 与 [TypeORM] 之间最需要理解的区别:使用 Spring Data 时,只需 声明一个接口 (extends CrudRepository<...>),就能自动获得基本方法(findAll、findOne、save、delete 等)——Spring 会在启动时自行生成实现它的类。而使用 [TypeORM] 时,不会根据接口自动生成实现:我们直接注入由 [TypeORM] 提供的通用 Repository<Entity>(通过 [@InjectRepository]),并自己编写想要公开的方法,这些方法基于该 Repository 的预定义方法,或者针对更特定的查询使用 查询构建器 。

4.5.1. src/repositories/doctor.repository.ts

  import { Injectable } from '@nestjs/common';
  import { InjectRepository } from '@nestjs/typeorm';
  import { Repository } from 'typeorm';
  import { Doctor } from '../entities/doctor.entity';

  @Injectable()
  export class DoctorRepository {
    constructor(
      @InjectRepository(Doctor)
     private readonly repository: Repository<Doctor>,
   ) {}

   findAll(): Promise<Doctor[]> {
     return this.repository.find();
   }

   findById(id: number): Promise<Doctor | null> {
     return this.repository.findOneBy({ id });
   }
 }

我们来解读这段代码:

  • 第 9 行:[@InjectRepository(Doctor)] ——请求 [NestJS] 提供 [TypeORM] 为 Doctor 实体自动生成的 Repository<[Doctor]>。这等价于对 Spring Data 生成的实现进行的自动注入(@Autowired);
  • 第 14 行:[return this.repository.find();] ——等价于 medecinRepository.findAll(),继承自 CrudRepository;
  • 第 18 行:[return this.repository.findOneBy({ id });] ——等价于 medecinRepository.findOne(id);如果没有医生具有该 ID,则返回 null(与 Spring Data 中的 findOne 一样,而不是抛出异常)。

4.5.2. src/repositories/client.repository.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Client } from '../entities/client.entity';

@Injectable()
export class ClientRepository {
  constructor(
    @InjectRepository(Client)
    private readonly repository: Repository<Client>,
  ) {}

  findAll(): Promise<Client[]> {
    return this.repository.find();
  }

  findById(id: number): Promise<Client | null> {
    return this.repository.findOneBy({ id });
  }
}

该文件在原理上与 [DoctorRepository] (见上文的说明)完全相同,只是应用于实体 [Client] (患者)。

4.5.3. src/repositories/slot.repository.ts

  import { Injectable } from '@nestjs/common';
  import { InjectRepository } from '@nestjs/typeorm';
  import { Repository } from 'typeorm';
  import { Slot } from '../entities/slot.entity';

  @Injectable()
  export class SlotRepository {
    constructor(
      @InjectRepository(Slot)
     private readonly repository: Repository<Slot>,
   ) {}

   findAll(): Promise<Slot[]> {
     return this.repository.find();
   }

   findById(id: number): Promise<Slot | null> {
     return this.repository.findOneBy({ id });
   }

   getAllSlots(doctorId: number): Promise<Slot[]> {
     return this.repository
       .createQueryBuilder('s')
       .where('s.doctor = :doctorId', { doctorId })
       .orderBy('s.startHour', 'ASC')
       .addOrderBy('s.startMinute', 'ASC')
       .getMany();
   }
 }

我们来解读这段代码:

  • 第 13–19 行:[findAll() / findById(id)] ——与 [DoctorRepository] 中已见过的原理相同;
  • 第 21 行:[getAllSlots(doctorId: number): Promise<Slot[]> {] ——一个“自定义”查询,等价于原来的 JPQL 查询 select c from [Creneau] c where c.medecin.[id]=?1;
  • 第 23 行:[.createQueryBuilder(‘s’)] ——命名了 SQL 别名 s,就像在 JPQL 中命名 [Creneau] c 一样;
  • 第 24 行:[.where(‘s.doctor = :doctorId’, { doctorId })] ——这里比较的是 关系 本身(s.doctor),而不是字段 [@RelationId] (s.doctorId):如上所述(slot.entity.ts),后者不是可用于 WHERE 的列。通过把关系与一个数字比较,[TypeORM] 能够识别出针对的是其外键,并生成正确的 SQL,而无需连接;
  • 第 25–26 行:[.orderBy(‘s.startHour’, ‘ASC’).addOrderBy(‘s.startMinute’, ‘ASC’)] ——按时间先后顺序对时间段排序,这是一个有用的补充,原 Spring 版本中并没有显式实现。

4.5.4. src/repositories/appointment.repository.ts

  import { Injectable } from '@nestjs/common';
  import { InjectRepository } from '@nestjs/typeorm';
  import { Repository } from 'typeorm';
  import { Appointment } from '../entities/appointment.entity';

  @Injectable()
  export class AppointmentRepository {
    constructor(
      @InjectRepository(Appointment)
     private readonly repository: Repository<Appointment>,
   ) {}

   findById(id: number): Promise<Appointment | null> {
     return this.repository.findOne({
       where: { id },
       relations: ['client', 'slot'],
     });
   }

   save(appointment: Appointment): Promise<Appointment> {
     return this.repository.save(appointment);
   }

   async deleteById(id: number): Promise<void> {
     await this.repository.delete(id);
   }

   getDoctorDayAppointments(doctorId: number, day: string): Promise<Appointment[]> {
     return this.repository
       .createQueryBuilder('appointment')
       .leftJoinAndSelect('appointment.client', 'client')
       .leftJoinAndSelect('appointment.slot', 'slot')
       .where('slot.doctor = :doctorId', { doctorId })
       .andWhere('appointment.day = :day', { day })
       .getMany();
   }
 }

我们来解读这段代码:

  • 第 13–18 行:[findById(id) { … relations: [‘client’, ‘slot’] }] ——关系:[...] 显式指示 [TypeORM] 同时加载相关联的客户(患者)和时间段(提醒:这些关系默认是“懒加载”模式;见 slot.entity.ts)——便于构造 JSON 响应(见下文的 getMapForAppointment);
  • 第 21 行:[return this.repository.save(appointment);] ——等价于 rvRepository.save(new Rv(jour, client, creneau));
  • 第 25 行:[await this.repository.delete(id);] ——等价于 rvRepository.delete(rv.getId());
  • 第 28 行:[getDoctorDayAppointments(doctorId: number, day: string): Promise<Appointment[]> {] ——等价于原来的 JPQL 查询 SELECT rv FROM Rv rv LEFT JOIN FETCH rv.client c LEFT JOIN FETCH rv.creneau cr WHERE cr.medecin.[id]=?1 and rv.[jour]=?2;
  • 第 31–32 行:[.leftJoinAndSelect(‘appointment.client’, ‘client’) / .leftJoinAndSelect(‘appointment.slot’, ‘slot’)] ——等价于原 JPQL 中的 LEFT JOIN FETCH:在一次 SQL 查询中取回与每个预约相关联的客户和时间段;
  • 第 33 行:[.where(‘slot.doctor = :doctorId’, { doctorId })] ——对医生的条件,通过与时间段的连接获得(JPQL 中为 rv.creneau.medecin.[id]=?1)——同样,我们比较的是“doctor”关系,而不是对应的 [@RelationId] 字段。

4.5.5. src/repositories/user.repository.ts

  import { Injectable } from '@nestjs/common';
  import { InjectRepository } from '@nestjs/typeorm';
  import { Repository } from 'typeorm';
  import { User } from '../entities/user.entity';

  @Injectable()
  export class UserRepository {
    constructor(
      @InjectRepository(User)
     private readonly repository: Repository<User>,
   ) {}

   findByLogin(login: string): Promise<User | null> {
     return this.repository.findOneBy({ login });
   }
 }

我们来解读这段代码:

  • 第 13 行:[findByLogin(login: string): Promise<User | null> {] ——这里所需的唯一查找方法,由登录过程使用(见 auth.service.ts):它取代了原项目中跨三张表按角色进行的查找,自从简化为单个 [role] 列后(见 user.entity.ts)这已不再必要。

4.6. 业务层(src/business/)

应用的业务规则就位于这里,且只位于这里——相当于原项目中的 rdvmedecins.metier 包。

4.6.1. src/business/business.interface.ts

  import { Client } from '../entities/client.entity';
  import { Slot } from '../entities/slot.entity';
  import { Doctor } from '../entities/doctor.entity';
  import { Appointment } from '../entities/appointment.entity';
  import { DoctorDaySchedule } from '../domain/doctor-day-schedule';

  export interface IBusiness {
    getAllClients(): Promise<Client[]>;
    getAllDoctors(): Promise<Doctor[]>;
   getAllSlots(doctorId: number): Promise<Slot[]>;
   getDoctorDayAppointments(doctorId: number, day: string): Promise<Appointment[]>;
   getClientById(id: number): Promise<Client | null>;
   getDoctorById(id: number): Promise<Doctor | null>;
   getAppointmentById(id: number): Promise<Appointment | null>;
   getSlotById(id: number): Promise<Slot | null>;
   addAppointment(day: string, slot: Slot, client: Client): Promise<Appointment>;
   deleteAppointment(appointment: Appointment): Promise<void>;
   getDoctorDaySchedule(doctorId: number, day: string): Promise<DoctorDaySchedule | null>;
 }

 export const BUSINESS_TOKEN = 'IBusiness';

我们来解读这段代码:

  • 第 7 行:[export interface IBusiness {] ——业务层的契约,独立于其实现——完全等价于原项目中的 Java 接口 [IMetier] ;
  • 第 8–18 行:十一个方法,分别对应应用的每项需求(列表、按 ID 查找、添加/删除预约、计算日程表);
  • 第 21 行:[export const BUSINESS_TOKEN = ‘IBusiness’;] ——我们定义一个注入“令牌”(InjectionToken),以便把这个接口注入控制器,正如 Spring 注入业务引用 [IMetier] 而不必知道其具体实现类 [Metier] 一样。在 TypeScript 中,接口在编译时会被擦除:因此不能直接用作注入令牌([NestJS]);这种变通做法是必要的(见其在 app.module.ts 和 application-model.service.ts 中的用法)。

4.6.2. src/business/business.service.ts

  import { Injectable } from '@nestjs/common';
  import { IBusiness } from './business.interface';
  import { DoctorRepository } from '../repositories/doctor.repository';
  import { ClientRepository } from '../repositories/client.repository';
  import { SlotRepository } from '../repositories/slot.repository';
  import { AppointmentRepository } from '../repositories/appointment.repository';
  // ……已导入的实体和业务对象(见上文)

  @Injectable()
 export class BusinessService implements IBusiness {
   constructor(
     private readonly doctorRepository: DoctorRepository,
     private readonly clientRepository: ClientRepository,
     private readonly slotRepository: SlotRepository,
     private readonly appointmentRepository: AppointmentRepository,
   ) {}

   getAllClients(): Promise<Client[]> { return this.clientRepository.findAll(); }
   getAllDoctors(): Promise<Doctor[]> { return this.doctorRepository.findAll(); }
   getAllSlots(doctorId: number): Promise<Slot[]> {
     return this.slotRepository.getAllSlots(doctorId);
   }
   // ……另外 5 个简单的委托方法(原理相同)

   addAppointment(day: string, slot: Slot, client: Client): Promise<Appointment> {
     const appointment = new Appointment();
     appointment.day = day;
     appointment.slot = slot;
     appointment.client = client;
     return this.appointmentRepository.save(appointment);
   }

   async deleteAppointment(appointment: Appointment): Promise<void> {
     await this.appointmentRepository.deleteById(appointment.id);
   }

   async getDoctorDaySchedule(doctorId: number, day: string): Promise<DoctorDaySchedule | null> {
     const doctor = await this.getDoctorById(doctorId);
     if (doctor === null) {
       return null;
     }
     const timeSlots = await this.getAllSlots(doctorId);
     const bookings = await this.getDoctorDayAppointments(doctorId, day);

     const hBookings = new Map<number, Appointment>();
     for (const booking of bookings) {
       hBookings.set(booking.slotId, booking);
     }

     const doctorDaySlots = timeSlots.map((slot) => {
       const appointment = hBookings.get(slot.id) ?? null;
       return new DoctorDaySlot(slot, appointment);
     });

     return new DoctorDaySchedule(doctor, day, doctorDaySlots);
   }
 }

我们来解读这段代码:

  • 第 10 行:[export class BusinessService implements IBusiness {] ——[@Injectable]() 等价于 @Service("métier"):该类成为一个“提供者”([NestJS]),[NestJS] 可以在需要的地方构造并注入它;
  • 第 11–16 行:[constructor(private readonly doctorRepository: …, …) {}] ——注入四个 DAO 实例,等价于原项目中的四个 @Autowired 字段。[NestJS] 在这里选择构造函数注入而不是字段注入(如 @Autowired 对 Java 字段所做的那样):这是 TypeScript 中推荐的做法;它使依赖关系显式化,并便于测试;
  • 第 18–23 行:大多数方法只是委托给 DAO 层——没有自定义的业务逻辑;
  • 第 25–31 行:[addAppointment(…) { const appointment = new Appointment(); … }]——创建一个新的 Appointment 实体并保存它;防止重复预约的是 SQL 约束 unq1_appointments(见上文的数据库脚本),而且仅靠它——这里不进行显式检查;重复尝试会触发 SQL 异常,并由 DAO 层向上传播;
  • 第 37 行:[async getDoctorDaySchedule(doctorId: number, day: string): Promise<DoctorDaySchedule | null> {] ——业务层中唯一 执行真正业务逻辑的方法(其他方法只是委托):它计算某位医生在给定日期的完整日程。算法与原文档完全一致,分为三步;
  • 第 42 行:[const timeSlots = await this.getAllSlots(doctorId);] ——1. 取回该医生所有可用的时间段;
  • 第 43 行:[const bookings = await this.getDoctorDayAppointments(doctorId, day);] ——2. 取回该医生在所请求日期的所有预约;
  • 第 45–48 行:[const hBookings = new Map<number, Appointment>(); …] ——这些预约存放在以时间段 ID 为索引的字典中,以便在下一步中快速取回——等价于原代码中的 `Map<Long, Rv> hReservations`;
  • 第 50–53 行:[const doctorDaySlots = timeSlots.map((slot) => { … })] ——3. 对每个时间段,检查它是否与找到的某个预约匹配:如果是,则为“已占用”(把找到的预约与它关联);否则为“空闲”(appointment = null)。

4.7. Web 层(src/web/)

这是应用的 HTTP 入口点——相当于原项目中的 [rdvmedecins.web] 包。

Image

4.7.1. src/web/models/response.model.ts

  export enum ResponseStatus {
    OK = 0,
    RESOURCE_NOT_FOUND = 1,
    INVALID_DATE = 2,
    SERVER_ERROR = 3,
  }

  export class ServerResponse<T = unknown> {
    status: ResponseStatus;
   data: T | null;

   constructor(status: ResponseStatus, data: T | null) {
     this.status = status;
     this.data = data;
   }

   static ok<T>(data: T): ServerResponse<T> {
     return new ServerResponse<T>(ResponseStatus.OK, data);
   }

   static error<T = unknown>(status: ResponseStatus, data: T | null = null): ServerResponse<T> {
     return new ServerResponse<T>(status, data);
   }
 }

我们来解读这段代码:

  • 第 1–6 行:[export enum ResponseStatus { … }] ——原 Spring 项目使用“临时的”数字(0、1、2、3、4……),其含义在不同的控制器方法之间各不相同。本次移植借机把所有可能的代码整合到 一个枚举中,更易学习和维护:客户端可观察到的行为(0 = 成功,其他任何值 = 失败)保持完全一致;
  • 第 8 行:[export class ServerResponse<T = unknown> {] ——Web 服务所有 JSON 响应的通用响应体:{ "status": 0, "data": ... }。与原版相比的新特性:借助 TypeScript,该类是 泛型的 ([ServerResponse]<T>),因此数据类型在编译时就已知(例如 [ServerResponse]<[Doctor][]>)——原项目的 Java 语言使用 `Object` 类型则不容易做到这一点;
  • 第 17–19 行:[static ok(data: T): ServerResponse {] ——一个小的静态“工厂”方法,使控制器代码更易读(ServerResponse.ok([doctors]) 而不是 new [ServerResponse](ResponseStatus.OK, [doctors]));
  • 第 21–23 行:[static error<T = unknown>(status: ResponseStatus, data: T | null = null): ServerResponse {] ——它对应错误响应的版本。

4.7.2. src/web/models/post-add-appointment.dto.ts

  import { IsDateString, IsInt } from 'class-validator';

  export class PostAddAppointmentDto {
    @IsDateString()
    day: string;

    @IsInt()
    clientId: number;

   @IsInt()
   slotId: number;
 }

我们来解读这段代码:

  • 第 3 行:[export class PostAddAppointmentDto {] ——描述 /addAppointment 路由所期望的 JSON 请求体的格式({ day, clientId, slotId })——一个“DTO”(数据传输对象,Data Transfer Object),其唯一目的是描述所交换数据的格式,不含任何逻辑;
  • 第 4 行:[@IsDateString()] ——验证收到的字符串确实是 ISO 格式的有效日期。如果不是,[NestJS] 会自动返回 HTTP 400 错误(Bad [Request]),在执行控制器之前 ——这得益于全局 [ValidationPipe] 在 [main.ts] 中的声明(见下文);
  • 第 7、10 行:[@IsInt()] ——验证收到的值确实是整数。这些装饰器与 [ValidationPipe] 结合,是 [NestJS] 中对应 Spring MVC 用 @RequestBody 执行的自动类型转换的机制。

4.7.3. src/web/models/post-delete-appointment.dto.ts

1
2
3
4
5
6
import { IsInt } from 'class-validator';

export class PostDeleteAppointmentDto {
  @IsInt()
  appointmentId: number;
}

原理与上文的 [PostAddAppointmentDto] 相同,用于 /deleteAppointment 所期望的 JSON 请求体({ appointmentId })。

4.7.4. src/web/helpers/static.helper.ts

  import { Slot } from '../../entities/slot.entity';
  import { Appointment } from '../../entities/appointment.entity';

  export function getErrorsForException(exception: unknown): string[] {
    const errors: string[] = [];
    let cause: unknown = exception;
    while (cause instanceof Error) {
      errors.push(cause.message);
      cause = cause.cause;
   }
   if (errors.length === 0) {
     errors.push(String(exception));
   }
   return errors;
 }

 export interface SlotJson {
   id: number; startHour: number; startMinute: number; endHour: number; endMinute: number;
 }

 export function getMapForSlot(slot: Slot | null | undefined): SlotJson | null {
   if (!slot) { return null; }
   return {
     id: slot.id, startHour: slot.startHour, startMinute: slot.startMinute,
     endHour: slot.endHour, endMinute: slot.endMinute,
   };
 }

 export function getListMapForSlots(slots: Slot[]): SlotJson[] {
   return slots.map((slot) => getMapForSlot(slot) as SlotJson);
 }

 export interface AppointmentJson {
   id: number;
   day: string;
   client: { id: number; title: string; lastName: string; firstName: string } | null;
   slot: SlotJson | null;
 }

 export function getMapForAppointment(appointment: Appointment | null | undefined): AppointmentJson | null {
   if (!appointment) { return null; }
   return {
     id: appointment.id,
     day: appointment.day,
     client: appointment.client
       ? { id: appointment.client.id, title: appointment.client.title, lastName: appointment.client.lastName, firstName: appointment.client.firstName }
       : null,
     slot: getMapForSlot(appointment.slot),
   };
 }

 export function getListMapForAppointments(appointments: Appointment[]): AppointmentJson[] {
   return appointments.map((appointment) => getMapForAppointment(appointment) as AppointmentJson);
 }

我们来解读这段代码:

  • 第 4 行:[export function getErrorsForException(exception: unknown): string[] {] ——等价于 Static.getErreursForException (Exception exception)。Java 可以链接异常(exception.getCause())来解释异常发生的“原因”;在现代 JavaScript/TypeScript(ES2022)中,错误同样有一条原因链,通过 `cause` 属性实现;
  • 第 6–10 行:[while (cause instanceof Error) { … cause = cause.cause; }] ——处理方式与原 Java 代码相同,把遇到的每条消息依次堆叠起来;
  • 第 17–19 行:[export interface SlotJson { … }] ——[Slot] 实体 不会原样以 JSON 返回:它包含一个指向“doctor”的关系,如果加载了它,就会重复客户端已知的信息(客户端已经知道所指的是哪位医生;见 URL 中的 {doctorId} 参数)。因此我们构造一个“自定义”对象,只包含显示所需的字段;
  • 第 21 行:[export function getMapForSlot(slot: Slot | null | undefined): SlotJson | null {] ——等价于 Static.getMapForCreneau([Creneau] creneau):把实体转换为轻量的 JSON 对象;
  • 第 29 行:[export function getListMapForSlots(slots: Slot[]): SlotJson[] {] ——它对应整个列表的版本(等价于 Static.getListMapForCreneaux);
  • 第 33–38、40–50、52–54 行:[AppointmentJson / getMapForAppointment / getListMapForAppointments] ——原理相同,应用于预约:嵌入的客户(appointment.client)同样被精简为仅包含显示所需的字段。

4.7.5. src/web/application-model.service.ts

  import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
  import { IBusiness, BUSINESS_TOKEN } from '../business/business.interface';
  // ……实体、DoctorDaySchedule、getErrorsForException(见上文)

  @Injectable()
  export class ApplicationModelService implements IBusiness, OnModuleInit {
    private doctors: Doctor[] = [];
    private clients: Client[] = [];
    private messages: string[] | null = null;

   constructor(@Inject(BUSINESS_TOKEN) private readonly business: IBusiness) {}

   async onModuleInit(): Promise<void> {
     try {
       this.doctors = await this.business.getAllDoctors();
       this.clients = await this.business.getAllClients();
     } catch (ex) {
       this.messages = getErrorsForException(ex);
     }
   }

   getMessages(): string[] | null {
     return this.messages;
   }

   async getAllClients(): Promise<Client[]> { return this.clients; }
   async getAllDoctors(): Promise<Doctor[]> { return this.doctors; }

   getAllSlots(doctorId: number): Promise<Slot[]> {
     return this.business.getAllSlots(doctorId);
   }
   // ……另外 6 个方法,简单地委托给 this.business
 }

我们来解读这段代码:

  • 第 6 行:[export class ApplicationModelService implements IBusiness, OnModuleInit {] ——等价于原项目中的 ApplicationModel 类:一个在服务器启动时一次性构建的缓存,把医生和客户(患者)列表存放在内存中(列表很短且很少变化,因此无需每次请求都查询数据库)。与原版一样,这个类有两个用途:一方面是缓存,另一方面是从控制器到业务层的 唯一 入口点——如果以后更改缓存策略,只需修改这个文件;
  • 第 11 行:[constructor(@Inject(BUSINESS_TOKEN) private readonly business: IBusiness) {}] ——这里,注入的是接口 [IBusiness](通过令牌 [BUSINESS_TOKEN],见 app.module.ts),而不是具体的类 [BusinessService]——正如原 Java 代码写 @Autowired private [IMetier] métier; 而从不提及 Metier 类一样;
  • 第 13 行:[async onModuleInit(): Promise<void> {] ——[OnModuleInit] 是 [NestJS] 的“生命周期”接口,其作用与 Spring 中的 @PostConstruct 完全相同:在该类的所有依赖都注入完毕后,onModuleInit() 会立即被 [NestJS] 自动调用;
  • 第 17–18 行:[catch (ex) { this.messages = getErrorsForException(ex); }]——如果启动时数据库不可用,错误会被捕获并存放在 `messages` 中,而不是导致服务器崩溃——与原项目的行为完全一致;
  • 第 26 行:[async getAllClients(): Promise<Client[]> { return this.clients; }] ——医生和客户(患者)列表来自缓存;其余一切(第 29 行及以后)都直接委托给业务层。

4.7.6. src/web/rdvmedecins.controller.ts

RdvMedecinsController 声明了应用的十一个路由,这些路由有意与原文档保持一致(/getAllDoctors、/addAppointment……,是 /getAllMedecins、/ajouterRv…… 的英文对应名称),而不是“现代化”的 REST 风格(/doctors、/clients/:id……)——本文档的目的是比较两种实现,而不是使 API 现代化。

  import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
  import { ApplicationModelService } from './application-model.service';
  import { ServerResponse, ResponseStatus } from './models/response.model';
  import { PostAddAppointmentDto } from './models/post-add-appointment.dto';
  import { PostDeleteAppointmentDto } from './models/post-delete-appointment.dto';
  import { getErrorsForException, getListMapForSlots, getListMapForAppointments, getMapForAppointment } from './helpers/static.helper';
  // ……实体
  import { JwtAuthGuard } from '../auth/jwt-auth.guard';
  import { RolesGuard } from '../auth/roles.guard';
 import { Roles } from '../auth/roles.decorator';

 @UseGuards(JwtAuthGuard)
 @Controller()
 export class RdvMedecinsController {
   constructor(private readonly application: ApplicationModelService) {}

   @Get('getAllDoctors')
   async getAllDoctors(): Promise<ServerResponse<Doctor[]>> {
     const messages = this.application.getMessages();
     if (messages !== null) {
       return new ServerResponse(ResponseStatus.SERVER_ERROR, messages as unknown as Doctor[]);
     }
     try {
       return ServerResponse.ok(await this.application.getAllDoctors());
     } catch (e) {
       return ServerResponse.error(ResponseStatus.SERVER_ERROR, getErrorsForException(e) as unknown as Doctor[]);
     }
   }

   // ……getAllClients:原理相同,针对 Client

   @Get('getAllSlots/:doctorId')
   async getAllSlots(@Param('doctorId') doctorId: string) {
     const id = Number(doctorId);
     const doctor = await this.application.getDoctorById(id);
     if (doctor === null) {
       return ServerResponse.error(ResponseStatus.RESOURCE_NOT_FOUND);
     }
     try {
       const slots = await this.application.getAllSlots(doctor.id);
       return ServerResponse.ok(getListMapForSlots(slots));
     } catch (e) {
       return ServerResponse.error(ResponseStatus.SERVER_ERROR, getErrorsForException(e));
     }
   }

   // ……getDoctorAppointmentsOfDay/:doctorId/:day:检查 isValidDate(day),然后原理相同

   @Get('getDoctorScheduleOfDay/:doctorId/:day')
   async getDoctorScheduleOfDay(@Param('doctorId') doctorId: string, @Param('day') day: string) {
     if (!isValidDate(day)) {
       return ServerResponse.error(ResponseStatus.INVALID_DATE);
     }
     try {
       const schedule = await this.application.getDoctorDaySchedule(Number(doctorId), day);
       if (schedule === null) {
         return ServerResponse.error(ResponseStatus.RESOURCE_NOT_FOUND);
       }
       return ServerResponse.ok({
         doctor: schedule.doctor,
         day: schedule.day,
         slots: schedule.doctorDaySlots.map((s) => ({
           slot: { id: s.slot.id, startHour: s.slot.startHour, startMinute: s.slot.startMinute, endHour: s.slot.endHour, endMinute: s.slot.endMinute },
           appointment: getMapForAppointment(s.appointment),
         })),
       });
     } catch (e) {
       return ServerResponse.error(ResponseStatus.SERVER_ERROR, getErrorsForException(e));
     }
   }

   // ……getDoctorById/:id、getClientById/:id、getSlotById/:id、getAppointmentById/:id:
   // 四个类似的方法,按 id 查找实体,找不到则返回 RESOURCE_NOT_FOUND

   @UseGuards(RolesGuard)
   @Roles('ADMIN')
   @Post('addAppointment')
   async addAppointment(@Body() post: PostAddAppointmentDto) {
     const client = await this.application.getClientById(post.clientId);
     if (client === null) {
       return ServerResponse.error(ResponseStatus.RESOURCE_NOT_FOUND);
     }
     const slot = await this.application.getSlotById(post.slotId);
     if (slot === null) {
       return ServerResponse.error(ResponseStatus.RESOURCE_NOT_FOUND);
     }
     try {
       const appointment = await this.application.addAppointment(post.day, slot, client);
       return ServerResponse.ok(getMapForAppointment(appointment));
     } catch (e) {
       return ServerResponse.error(ResponseStatus.SERVER_ERROR, getErrorsForException(e));
     }
   }

   @UseGuards(RolesGuard)
   @Roles('ADMIN')
   @Post('deleteAppointment')
   async deleteAppointment(@Body() post: PostDeleteAppointmentDto) {
     const appointment = await this.application.getAppointmentById(post.appointmentId);
    if (appointment === null) {
      return ServerResponse.error(ResponseStatus.RESOURCE_NOT_FOUND);
    }
    try {
      await this.application.deleteAppointment(appointment);
      return ServerResponse.ok(null);
    } catch (e) {
      return ServerResponse.error(ResponseStatus.SERVER_ERROR, getErrorsForException(e));
    }
  }
 }

 function isValidDate(day: string): boolean {
   if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) {
     return false;
   }
   const date = new Date(`${day}T00:00:00Z`);
   return date.toISOString().slice(0, 10) === day;
 }

我们来解读这段代码:

  • 第 12 行:[@UseGuards(JwtAuthGuard)] ——应用于 类,一次性保护该控制器的全部十一个路由:没有有效的 JWT 令牌,任何一个都无法访问(见下文的“身份验证”一章)。这等价于原 Spring Security 规则 .antMatchers("/**").hasRole("ADMIN"),只是这里唯一的要求是通过身份验证(任何角色)——对 ADMIN 角色的限制只适用于两个修改数据的路由(第 75–76 行和第 95–96 行);
  • 第 13 行:[@Controller()] ——没有前缀:因此路由恰好是 /getAllDoctors、/getAllClients 等。这等价于 Spring 中的 @RestController:方法返回的每个值都会自动序列化为 JSON;
  • 第 15 行:[constructor(private readonly application: ApplicationModelService) {}] ——缓存/外观的注入,等价于 @Autowired private ApplicationModel application;;
  • 第 19–22 行:[const messages = this.application.getMessages(); if (messages !== null) { … }] ——首先验证应用已正确初始化(见 ApplicationModelService.onModuleInit),等价于 `if (messages != null) { return new [Reponse](-1, messages); }`;
  • 第 33 行:[async getAllSlots(@Param('doctorId') doctorId: string) {] ——[@Param]('doctorId') 以字符串形式获取 URL 中的片段 {doctorId}(类似于 Spring 中的 @PathVariable(String));我们自己把它转换为数字(第 34 行),而对于声明为 `long` 的参数,Spring 会自动完成这一转换;
  • 第 35–38 行:[const doctor = await this.application.getDoctorById(id); if (doctor === null) { … }] ——我们先取回医生,验证其存在,然后再继续(等价于原控制器中的私有方法 getMedecin(id));
  • 第 41 行:[return ServerResponse.ok(getListMapForSlots(slots));] ——把实体 [Slot] 列表转换为“轻量”JavaScript 对象的列表(见 static.helper.ts);
  • 第 59 行:[return ServerResponse.ok({ doctor: …, day: …, slots: … });] ——日程表以“精简”形式格式化为 JSON,原则与 getMapForSlot/getMapForAppointment 相同;
  • 第 75 行:[@UseGuards(RolesGuard)],然后是第 76 行:[@Roles('ADMIN')] ——除了需要通过身份验证(类上的 [@UseGuards]([JwtAuthGuard])已经要求这一点)之外,这里还必须具有角色 ADMIN——角色 USER 会收到 403 Forbidden 响应(见 roles.guard.ts)。[RolesGuard] 读取 request.user(由 JwtAuthGuard/JwtStrategy 提交):因此它必须在 之后[JwtAuthGuard] 运行([NestJS] 先应用类守卫,再按出现的顺序应用方法守卫);
  • 第 87–92 行:[try { const appointment = await this.application.addAppointment(…); … } catch (e) { … }] ——此时,class-validator(见 [PostAddAppointmentDto])已经验证 post.[day] 是有效日期,且 post.clientId/post.slotId 确实是整数。SQL 约束 unq1_appointments (day, slot_id) 可防止同一天的同一个时间段被预约两次:重复尝试会抛出异常,并在这里被捕获,与原 JDBC 驱动抛出的 SQLException 完全一样;
  • 第 95 行:与第 75 行的限制相同,用于 deleteAppointment:只有角色 ADMIN 才能取消预约;
  • 第 112 行:[function isValidDate(day: string): boolean {] ——一个小的本地工具函数,等价于原代码中 SimpleDateFormat("yyyy-MM-dd") + setLenient(false) 这一对用法,后者会拒绝例如“2026-13-40”(无效的月份和日期):Date.toISOString() 根据收到的字符串重建日期——如果它与输入不同,就说明该日期不存在。

4.8. 身份验证(src/auth/)

Image

本节记录在课程这一阶段加入的基于令牌的身份验证(JWT)和基于角色的访问控制(ADMIN/USER)——在功能上等价于原文档中的 Spring Security 层,使用 [NestJS] 生态中的标准工具重写:[@nestjs/passport] 和 @nestjs/jwt。

与原项目的两个有意设置的差异,在此一次性说明:

  1. 使用 JWT 而不是 HTTP Basic。原 Spring 项目在 每个请求中都发送 Authorization: Basic <Base64 编码的 login:password> 请求头:因此密码(经过编码,而非加密)在每次调用时都会在网络上传输。本次移植改用 令牌:JWT (JSON Web Token)。密码 只提交一次,即登录时(POST /login);服务器随后返回一个已签名的令牌,客户端在之后的每个请求中都携带它(Authorization: Bearer <token> 请求头)。这是此类 API 当前的通行做法,正如上一章的结论中已经提到的。
  2. 每个用户一个角色,数据库中的单个列,而不是原项目中的多对多关系(users/roles/users_roles)——见上文的 user.entity.ts。

阅读后面的代码之前需要理解的一个架构要点:当守卫拒绝请求时(401 Unauthorized、403 Forbidden),响应绝不会经过通常的 [ServerResponse]<T> 信封({ status, data }):[NestJS] 直接以其原生 JSON 格式响应,即 { statusCode, message, error }。这是有意的选择:安全错误由守卫在进入控制器 之前 处理,而 [ServerResponse]<T> 是由 控制器针对 业务错误(资源未找到、日期无效等)生成的。因此,[React] 客户端必须区分这两类错误响应(见下一章的 auth.interceptor.ts)。

4.8.1. src/auth/dto/login.dto.ts

import { IsNotEmpty, IsString } from 'class-validator';

export class LoginDto {
  @IsString()
  @IsNotEmpty()
  login: string;

  @IsString()
  @IsNotEmpty()
  password: string;
}

我们来解读这段代码:

  • 第 3 行:[export class LoginDto {] ——描述 POST /login 所期望的 JSON 请求体的格式({ login, password }),机制与 src/web/models 中已经见过的 DTO 相同;
  • 第 4–5、8–9 行:[@IsString() @IsNotEmpty()] ——验证两个字段都是 非空的字符串。

这个 DTO 在这里纯粹起 说明作用:实际上从请求体中读取 {login, password} 的是 [LocalStrategy] (见下文),而不是控制器的 [@Body]([LoginDto])参数——尽管如此,[LoginDto] 能向读者说明该路由所期望的确切格式。

4.8.2. src/auth/login-result.model.ts

1
2
3
4
5
6
7
8
  import { Role } from '../entities/user.entity';

  export interface LoginResult {
    accessToken: string;
    login: string;
    name: string;
    role: Role;
  }

我们来解读这段代码:

  • 第 3 行:[export interface LoginResult {] ——POST /login 成功时返回的数据格式,放在标准的 [ServerResponse]<T> 信封中:{ "status": 0, "data": { accessToken, login, name, role } };
  • 第 4 行:[accessToken: string;] ——要在每个后续请求中携带的 JWT 令牌;
  • 第 7 行:[role: Role;] ——已登录用户的角色,以便 [React] 客户端可以调整其界面(见下一章,对 USER 角色隐藏“预约”/“取消”按钮)。

4.8.3. src/auth/local.strategy.ts

Passport“策略”描述 如何验证请求的身份。[LocalStrategy] 可以从 POST 请求的请求体中读取 {login, password} 对,并把验证工作委托给 AuthService。它 只使用一次,由路由 POST /login 使用(通过 [LocalAuthGuard]):之后所有其他受保护的路由使用的是 [JwtStrategy] (见下文),而不是这一个。

  import { Injectable, UnauthorizedException } from '@nestjs/common';
  import { PassportStrategy } from '@nestjs/passport';
  import { Strategy } from 'passport-local';
  import { AuthService } from './auth.service';
  import { User } from '../entities/user.entity';

  @Injectable()
  export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly authService: AuthService) {
     super({ usernameField: 'login', passwordField: 'password' });
   }

   async validate(login: string, password: string): Promise<User> {
     const user = await this.authService.validateUser(login, password);
     if (user === null) {
       throw new UnauthorizedException('incorrect login or password');
     }
     return user;
   }
 }

我们来解读这段代码:

  • 第 8 行:[export class LocalStrategy extends PassportStrategy(Strategy) {] ——在概念上等价于原 Spring Security 项目中的 AppUserDetailsService 类:“给定一些凭据,告诉我这个用户是谁”;
  • 第 10 行:[super({ usernameField: ‘login’, passwordField: ‘password’ });] ——默认情况下,passport-local 期望请求体中的字段名为“username”和“password”;这里我们将其重命名,以与我们的 DTO([LoginDto])一致,后者使用“login”而不是“username”;
  • 第 13 行:[async validate(login: string, password: string): Promise<User> {] ——由 Passport 用从请求中提取的两个字段自动调用。它返回的内容会成为控制器中的 request.user(见 auth.controller.ts);
  • 第 16 行:[throw new UnauthorizedException(‘incorrect login or password’);] ——Passport 会自动把这个异常转换为 HTTP 401 Unauthorized 响应,在它甚至到达控制器之前。

4.8.4. src/auth/jwt.strategy.ts

第二个 Passport 策略:它可以从 HTTP Authorization: Bearer <token> 请求头中读取 JWT 令牌,该请求头来自 每个请求,验证其签名,并提取用户的身份——全程无需查询数据库(令牌已经包含所需的一切)。这就是保护 RdvMedecinsController 十一个路由的机制。

  import { Injectable } from '@nestjs/common';
  import { PassportStrategy } from '@nestjs/passport';
  import { ExtractJwt, Strategy } from 'passport-jwt';

  export interface JwtPayload {
    sub: number;
    login: string;
    role: 'ADMIN' | 'USER';
  }

 export interface ConnectedUser {
   userId: number;
   login: string;
   role: 'ADMIN' | 'USER';
 }

 @Injectable()
 export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
   constructor() {
     super({
       jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
       ignoreExpiration: false,
       secretOrKey: process.env.JWT_SECRET ?? 'dev-secret-to-change-in-production',
     });
   }

   validate(payload: JwtPayload): ConnectedUser {
     return { userId: payload.sub, login: payload.login, role: payload.role };
   }
 }

我们来解读这段代码:

  • 第 5–9 行:[export interface JwtPayload { sub: number; login: string; role: … }] ——我们选择在生成 JWT 令牌时存放 在 令牌中的信息的格式(见 auth.service.ts);sub(“subject”)是 JWT 中约定俗成的名称,表示包含用户标识符的字段;
  • 第 11–15 行:[export interface ConnectedUser { … }] ——令牌验证通过后,request.user 在处理函数中所包含的内容;
  • 第 18 行:[export class JwtStrategy extends PassportStrategy(Strategy, ‘jwt’) {] ——第二个参数 'jwt' 为该策略命名(不同于 [LocalStrategy],它没有指定名称):这就是 [JwtAuthGuard] ([AuthGuard]('jwt'),见下文)用来表示“使用 这个 策略”的名称;
  • 第 21 行:[jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),] ——令牌应位于 Authorization: Bearer xxx 请求头中;
  • 第 22 行:[ignoreExpiration: false,] ——如果令牌已过期,Passport 会在调用 validate() 之前就拒绝它(401);
  • 第 23 行:[secretOrKey: process.env.JWT_SECRET ?? ‘…’] ——用于 验证 令牌签名的密钥——与用于 签名 的密钥相同(见 auth.module.ts,它从同一个环境变量 JWT_SECRET 读取);
  • 第 27 行:[validate(payload: JwtPayload): ConnectedUser {] ——令牌签名验证通过后由 Passport 自动调用;把令牌的内容转换为 request.user。

4.8.5. src/auth/local-auth.guard.ts

1
2
3
4
5
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

我们来解读这段代码:

  • 第 5 行:[export class LocalAuthGuard extends AuthGuard(‘local’) {}] ——“守卫”([NestJS])在控制器方法执行之前,判断请求是否有权访问它。[AuthGuard]('local') 是 [@nestjs/passport] 提供的工厂,它基于名为 'local' 的 Passport 策略构造守卫(隐式地指 [LocalStrategy],它在自己的构造函数中没有被指定显式的名称)。这个守卫只被路由 POST /login 使用(见 auth.controller.ts)。

4.8.6. src/auth/jwt-auth.guard.ts

1
2
3
4
5
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

我们来解读这段代码:

  • 第 5 行:[export class JwtAuthGuard extends AuthGuard(‘jwt’) {}] ——保护 RdvMedecinsController 十一个路由的守卫:它要求提供有效的 JWT 令牌(“jwt”指 [JwtStrategy];见上文)。没有令牌,或令牌无效或已过期时,[NestJS] 会自动响应 401 Unauthorized 错误——甚至在到达控制器之前。

4.8.7. src/auth/roles.decorator.ts

1
2
3
4
5
import { SetMetadata } from '@nestjs/common';
import { Role } from '../entities/user.entity';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

我们来解读这段代码:

  • 第 5 行:[export const Roles = (…roles: Role[]) => SetMetadata(ROLES_KEY, roles);] ——[@Roles]('ADMIN') 是一个 自定义 装饰器(由我们自己编写,不同于由 [NestJS] 提供的 @Get、@Post 和 @Injectable):它只是把元数据(“此方法需要某某角色”)附加到它所装饰的方法上,自己不执行任何检查——读取这些元数据并执行检查的是 [RolesGuard] (见下文)。[SetMetadata](key, value) 是 [NestJS] 的底层函数,可让您编写这类“自己的”装饰器。

4.8.8. src/auth/roles.guard.ts

第二层验证,紧随 [JwtAuthGuard]:该守卫只验证用户已通过身份验证(有效的 JWT 令牌);[RolesGuard] 还会进一步验证已登录用户的角色是否属于目标方法上 [@Roles](...) 所要求的角色之一。

  import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
  import { Reflector } from '@nestjs/core';
  import { ROLES_KEY } from './roles.decorator';
  import { Role } from '../entities/user.entity';
  import { ConnectedUser } from './jwt.strategy';

  @Injectable()
  export class RolesGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) {}

   canActivate(context: ExecutionContext): boolean {
     const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
       context.getHandler(),
       context.getClass(),
     ]);

     if (!requiredRoles || requiredRoles.length === 0) {
       return true;
     }

     const request = context.switchToHttp().getRequest<{ user: ConnectedUser }>();
     const user = request.user;

     if (!requiredRoles.includes(user.role)) {
       throw new ForbiddenException(
         `role [${user.role}] does not allow this action (required role: ${requiredRoles.join(', ')})`,
       );
     }
     return true;
   }
 }

我们来解读这段代码:

  • 第 8 行:[export class RolesGuard implements CanActivate {] ——在概念上等价于 Spring Security 规则 http.authorizeRequests().antMatchers(...).hasRole("ADMIN"),但这里借助装饰器([@Roles])+ [Reflector](可以重新读取由装饰器设置的元数据)这一组合,是逐个方法而不是逐个 URL 地应用;
  • 第 12 行:[const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, […])] ——在目标方法上读回由 [@Roles](...) 设置的元数据——getAllAndOverride 先查找方法(第 13 行),再查找类(第 14 行);
  • 第 17–19 行:[if (!requiredRoles || requiredRoles.length === 0) { return true; }] ——该方法没有 [@Roles](...) 元数据:没有额外的角色限制(不过,[JwtAuthGuard] 已经要求了有效的身份验证,与角色无关);
  • 第 21 行:[const request = context.switchToHttp().getRequest<{ user: ConnectedUser }>();] ——request.user 由 JwtStrategy.validate() 提交:[RolesGuard] 因此总是在 [JwtAuthGuard] 之后执行(见它们在 [@UseGuards](...) 中的顺序,rdvmedecins.controller.ts);
  • 第 24–28 行:[if (!requiredRoles.includes(user.role)) { throw new ForbiddenException(…); }] ——如果已登录用户的角色不属于所要求的角色之一,就会抛出 403 Forbidden 异常,并附带说明收到的角色和期望角色的消息。

4.8.9. src/auth/auth.service.ts

处理全部身份验证逻辑的服务:验证用户名/密码对,并在用户通过验证后生成发回给客户端的 JWT 令牌。

  import { Injectable } from '@nestjs/common';
  import { JwtService } from '@nestjs/jwt';
  import * as bcrypt from 'bcryptjs';
  import { UserRepository } from '../repositories/user.repository';
  import { User } from '../entities/user.entity';
  import { LoginResult } from './login-result.model';
  import { JwtPayload } from './jwt.strategy';

  @Injectable()
 export class AuthService {
   constructor(
     private readonly userRepository: UserRepository,
     private readonly jwtService: JwtService,
   ) {}

   async validateUser(login: string, password: string): Promise<User | null> {
     const user = await this.userRepository.findByLogin(login);
     if (user === null) {
       return null;
     }
     const passwordCorrect = await bcrypt.compare(password, user.password);
     return passwordCorrect ? user : null;
   }

   login(user: User): LoginResult {
     const payload: JwtPayload = { sub: user.id, login: user.login, role: user.role };
     return {
       accessToken: this.jwtService.sign(payload),
       login: user.login,
       name: user.name,
       role: user.role,
     };
   }
 }

我们来解读这段代码:

  • 第 10 行:[export class AuthService {] ——在概念上等价于原 Spring Security 项目中的 AppUserDetailsService 类,这里与令牌生成合并在一起;
  • 第 16 行:[async validateUser(login: string, password: string): Promise<User | null> {] ——验证存在使用该 login 的用户,且所提供的密码与之匹配;一切正确则返回该用户,否则返回 null;
  • 第 21 行:[const passwordCorrect = await bcrypt.compare(password, user.password);] ——bcrypt.compare() 使用相同的 盐(即存储在 user.[password] 中的盐)对密码进行哈希,然后比较两个结果——存储的密码绝不会被解密(哈希不可逆);
  • 第 25 行:[login(user: User): LoginResult {] ——为已通过身份验证的用户生成 JWT 令牌(在 LocalAuthGuard 和 LocalStrategy 成功完成后,由 [AuthController] 调用);
  • 第 28 行:[accessToken: this.jwtService.sign(payload),] ——jwtService.sign() 使用在 auth.module.ts(JwtModule.register)中配置的密钥和过期时间对载荷进行签名。

4.8.10. src/auth/auth.controller.ts

只有一个路由:POST /login。这是整个应用中 唯一 一个 不要求 JWT 令牌的路由(因为它正是签发令牌的路由)。

  import { Controller, Post, Request, UseGuards } from '@nestjs/common';
  import { LocalAuthGuard } from './local-auth.guard';
  import { AuthService } from './auth.service';
  import { ServerResponse } from '../web/models/response.model';
  import { LoginResult } from './login-result.model';
  import { User } from '../entities/user.entity';

  @Controller()
  export class AuthController {
   constructor(private readonly authService: AuthService) {}

   @UseGuards(LocalAuthGuard)
   @Post('login')
   login(@Request() req: { user: User }): ServerResponse<LoginResult> {
     return ServerResponse.ok<LoginResult>(this.authService.login(req.user));
   }
 }

我们来解读这段代码:

  • 第 12 行:[@UseGuards(LocalAuthGuard)] ——把该守卫置于方法之前:它会触发 LocalStrategy.validate(),验证 login/password 对。如果验证失败,[NestJS] 会返回 401 Unauthorized 响应,甚至在执行该方法的主体之前;
  • 第 14 行:[login(@Request() req: { user: User }): ServerResponse<LoginResult> {] ——如果执行到这里,说明 [LocalAuthGuard] 已成功:req.user 包含 LocalStrategy.validate() 返回的用户。注意这里没有 [@Body]([LoginDto])参数:从请求体中读取 {login, password} 的是守卫,而不是这个方法;
  • 第 15 行:[return ServerResponse.ok(this.authService.login(req.user));] ——生成 JWT 令牌并把它包装在标准的 [ServerResponse]<T> 响应中——不同于守卫的 401/403 响应(见上文),成功的连接 会经过这个包装。

4.8.11. src/auth/auth.module.ts

处理与身份验证相关的一切的模块。只被 AppModule 导入一次。

  import { Module } from '@nestjs/common';
  import { JwtModule } from '@nestjs/jwt';
  import { PassportModule } from '@nestjs/passport';
  import { TypeOrmModule } from '@nestjs/typeorm';
  import { User } from '../entities/user.entity';
  import { UserRepository } from '../repositories/user.repository';
  import { AuthService } from './auth.service';
  import { AuthController } from './auth.controller';
  import { LocalStrategy } from './local.strategy';
 import { JwtStrategy } from './jwt.strategy';

 @Module({
   imports: [
     TypeOrmModule.forFeature([User]),
     PassportModule,
     JwtModule.register({
       secret: process.env.JWT_SECRET ?? 'dev-secret-to-change-in-production',
       signOptions: { expiresIn: process.env.JWT_EXPIRES_IN ?? '2h' },
     }),
   ],
   controllers: [AuthController],
   providers: [
     AuthService,
     UserRepository,
     LocalStrategy,
     JwtStrategy,
   ],
 })
 export class AuthModule {}

我们来解读这段代码:

  • 第 14 行:[TypeOrmModule.forFeature([User]),] ——使 Repository<[User]> 可被注入(见 repositories/user.repository.ts);
  • 第 15 行:[PassportModule,] ——声明 'jwt' 为不带参数的 [AuthGuard]() 的默认策略;我们的守卫仍然显式指定 [AuthGuard]('local')/AuthGuard('jwt'),以保持可读性;
  • 第 16–19 行:[JwtModule.register({ secret: …, signOptions: { expiresIn: … } }),] ——配置令牌的生成与验证:签名所用的密钥(JWT_SECRET,见 .env)及其有效期(JWT_EXPIRES_IN,例如 "2h");
  • 第 25–26 行:[LocalStrategy, JwtStrategy,] ——分别向 Passport 注册 'local' 和 'jwt' 策略;如果没有在 `providers` 中进行这一声明,[NestJS] 就无法构造这两个类。

4.9. 配置与启动

4.9.1. package.json

{
  "name": "rdvmedecins-nestjs-server",
  "version": "1.0.0",
  "description": "NestJS server of the medical appointment booking application [RdvMedecins] - port of the original Spring 4 / Spring Data server",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "build": "nest build",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main"
  },
  "dependencies": {
    "@nestjs/common": "^10.4.0",
    "@nestjs/core": "^10.4.0",
    "@nestjs/jwt": "^10.2.0",
    "@nestjs/passport": "^10.0.3",
    "@nestjs/platform-express": "^10.4.0",
    "@nestjs/typeorm": "^10.0.2",
    "bcryptjs": "^3.0.3",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.1",
    "dotenv": "^17.4.2",
    "mysql2": "^3.11.0",
    "passport-jwt": "^4.0.1",
    "passport-local": "^1.0.0",
    "reflect-metadata": "^0.2.2",
    "rxjs": "^7.8.1",
    "typeorm": "^0.3.20"
  },
  "devDependencies": {
    "@nestjs/cli": "^10.4.5",
    "@types/bcryptjs": "^2.4.6",
    "@types/node": "^20.14.0",
    "@types/passport-jwt": "^4.0.1",
    "@types/passport-local": "^1.0.38",
    "typescript": "^5.5.0"
  }
}

我们来解读这段代码:

  • 第 7–13 行:[“scripts”: { … }] ——可用的 `npm run <name>` 命令。start:dev(本文档全程使用)会在 .ts 文件被修改时自动重新编译并重启服务器([NestJS] CLI 的 --watch 选项,相当于 Spring Boot 的 devtools)。start:prod 直接启动预编译的 JavaScript(dist/main.js),无需经过 CLI 也无需重新编译——这是在生产环境中使用的模式;
  • 第 14–31 行:[“dependencies”: { … }]——运行服务器所需的包。其中包含 [NestJS] 的核心([@nestjs/common]、[@nestjs/core]、[@nestjs/platform-express])、[TypeORM] 的集成包([@nestjs/typeorm]、typeorm、mysql2——[MySQL] 驱动,由 [TypeORM]使用)、基于 DTO 的验证(class-validator、class-transformer)、读取 .env 文件(dotenv),以及——由身份验证提供(见下一章)——[@nestjs/jwt] 和 [@nestjs/passport] (Passport.js 与 [NestJS] 的集成)、passport-jwt/passport-local(使用的两个 Passport 策略)和 bcryptjs(密码哈希);
  • 第 32–39 行:[“devDependencies”: { … }] ——仅在 开发 期间需要的包(编译、类型),绝不会包含在 dist/ 中:[NestJS] CLI 本身([@nestjs/cli])、TypeScript 编译器,以及未原生提供类型的 JavaScript 包(bcryptjs、passport-jwt、passport-local)的类型定义(@types/...)。

与 [React] 客户端一样(见下一章),这就是 [npm install] 读取的文件(第 1 章),用来确定要往 node_modules/ 中下载什么——相当于 Node/TypeScript 生态中原 Spring 项目的 pom.xml。

4.9.2. [tsconfig.json]

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2022",
    "lib": ["ES2022"],
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": false
  }
}

我们来解读这段代码:

  • 第 3 行:[“module”: “commonjs”,] ——编译产生的 JavaScript 模块的格式;对于这类服务器端项目,commonjs(require/module.exports)仍然是 Node.js 期望的格式,而不是在客户端([React])看到的 ESM 格式(原生的 import/export);
  • 第 6–7 行:[“emitDecoratorMetadata”: true, “experimentalDecorators”: true,] ——这两个选项对于 [NestJS](以及 [TypeORM])能够运行至关重要:它们启用对装饰器([@Controller]()、[@Injectable]()、[@Entity]() 等)的支持,而且最重要的是,确保编译器在运行时保留每个构造函数参数的类型——这就是 [NestJS] 读取以自行判断要注入什么的信息(见第 2 章中关于依赖注入的一节)。没有这两行,构造函数注入就根本无法工作;
  • 第 9 行:[“target”: “ES2022”,]——编译产生的 JavaScript 版本;ES2022 被本课程使用的 Node.js 版本(20+)广泛支持,可让您在源代码中直接使用较新的 JavaScript 特性(类私有字段 #x、Array.at() 等);
  • 第 16 行:[“strictNullChecks”: true,] ——要求显式处理 null/undefined 值(使用 ?、??、if 语句……)——这是 TypeScript 严格模式的选项之一,这里单独启用它,而不是启用完整的严格模式(第 17 行:noImplicitAny 仍设为 false,限制更宽松):这是一种教学上的折中,既保留类型安全的精髓,又不要求为每个变量都添加类型注解。

4.9.3. nest-cli.json

1
2
3
4
5
6
7
8
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true
  }
}

我们来解读这段代码:

  • 第 3 行:[“collection”: “@nestjs/schematics”,] ——`nest generate ...` 命令使用的代码生成器(本文档中未使用,因为所有文件都是手工编写的,但在课程的其余部分可以使用);
  • 第 4 行:[“sourceRoot”: “src”,] ——告诉 [NestJS] CLI 要编译的源代码位于何处——正因如此,它才能知道,例如,入口点是 [src/main.ts];
  • 第 6 行:[“deleteOutDir”: true] ——每次编译之前,dist/ 文件夹([tsconfig.json] 中的 outDir 行)会被彻底清空:这样可以避免由已被删除的 .ts 文件编译出的 .js 文件无限期地残留在 dist/ 中。

这个文件是 [NestJS] 生态所特有的:在 [React] 项目中没有与之直接对应的文件(见下一章),其中 vite.config.ts 起着相当类似的作用。

4.9.4. src/config/database.config.ts

Image

  import { TypeOrmModuleOptions } from '@nestjs/typeorm';
  import { Doctor } from '../entities/doctor.entity';
  import { Client } from '../entities/client.entity';
  import { Slot } from '../entities/slot.entity';
  import { Appointment } from '../entities/appointment.entity';
  import { User } from '../entities/user.entity';

  export function getDatabaseConfig(): TypeOrmModuleOptions {
    return {
     type: 'mysql',
     host: process.env.DB_HOST ?? 'localhost',
     port: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 3306,
     username: process.env.DB_USERNAME ?? 'root',
     password: process.env.DB_PASSWORD ?? '',
     database: process.env.DB_DATABASE ?? 'dbrdvmedecins',
     entities: [Doctor, Client, Slot, Appointment, User],
     synchronize: false,
     logging: process.env.NODE_ENV !== 'production',
   };
 }

我们来解读这段代码:

  • 第 8 行:[export function getDatabaseConfig(): TypeOrmModuleOptions {] ——等价于原 Spring 项目中的 DomainAndPersitenceConfig 类,它定义了一个 DataSource(@Bean 块)。这里没有类:只是一个简单的函数,返回从环境变量(.env 文件;见下文)读取的配置对象;
  • 第 16 行:[entities: [Doctor, Client, Slot, Appointment, User],] ——[TypeORM] 必须管理的实体列表——等价于 Spring Boot 对 [@Entity] 类执行的自动“扫描”。[User] 是随着身份验证的加入而添加到此列表中的:如果漏掉它,启动时会出现“no metadata found for [User]”错误;
  • 第 17 行:[synchronize: false,] ——在本课程中始终存在:如果将 `synchronize` 设为 `true`,[TypeORM] 就会根据实体自动修改数据库模式——对于一次性的原型很有用,但一旦涉及真实数据就很危险(有数据丢失的风险)。我们通过脚本 [database/dbrdvmedecins.sql] 来掌控模式;
  • 第 18 行:[logging: process.env.NODE_ENV !== ‘production’,] ——在控制台中显示由 [TypeORM] 生成的 SQL 查询,与原 Spring 项目中的 Hibernate 日志完全一样。

4.9.5. [src/main.ts]

Image

  import 'dotenv/config';
  import 'reflect-metadata';
  import { NestFactory } from '@nestjs/core';
  import { ValidationPipe } from '@nestjs/common';
  import { AppModule } from './app.module';

  async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.enableCors();
   app.useGlobalPipes(
     new ValidationPipe({
       transform: true,
       whitelist: true,
     }),
   );
   const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 8080;
   await app.listen(port);
   console.log(`[RdvMedecins] NestJS server started on http://localhost:${port}`);
 }

 bootstrap();

我们来解读这段代码:

  • 第 1 行:[import ‘dotenv/config’;] ——必须是该文件中的第一个导入:其唯一目的是读取 .env 文件,并在其他任何内容被求值之前,把其内容复制到 process.env 中——具体来说,是在 app.module.ts(第 5 行导入)进而加载 database.config.ts 和 auth/auth.module.ts 之前,这两个文件一加载就会读取 process.env(DB_HOST、JWT_SECRET……)。如果没有这一行,或者它不在这个特定位置,磁盘上的 .env 文件就毫无用处:当这些模块需要这些变量时,process.env 中根本不存在它们;
  • 第 8 行:[const app = await NestFactory.create(AppModule);] ——从根模块构建应用——等价于 SpringApplication.run(Boot.class, args);
  • 第 9 行:[app.enableCors();] ——授权 [React] 客户端(运行在另一个端口上)调用此服务器。没有它,浏览器出于安全原因会阻止这些请求;
  • 第 10–15 行:[app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));] ——对每个传入的请求,自动验证 JSON 请求体是否符合期望的格式(见用 class-validator 装饰的类);`transform: true` 自动转换类型(例如字符串“3”→ 数字 3),`whitelist: true` 会从收到的数据中删除未在 `DTO` 中声明的字段;
  • 第 16 行:[const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 8080;] ——默认端口 8080 与原 Spring Boot 服务器的端口相同。

4.9.6. src/app.module.ts

  import { Module } from '@nestjs/common';
  import { TypeOrmModule } from '@nestjs/typeorm';
  import { getDatabaseConfig } from './config/database.config';
  // ……实体、仓库、BUSINESS_TOKEN/BusinessService、ApplicationModelService、RdvMedecinsController
  import { AuthModule } from './auth/auth.module';

  @Module({
    imports: [
      TypeOrmModule.forRoot(getDatabaseConfig()),
     TypeOrmModule.forFeature([Doctor, Client, Slot, Appointment]),
     AuthModule,
   ],
   controllers: [
     RdvMedecinsController,
   ],
   providers: [
     DoctorRepository,
     ClientRepository,
     SlotRepository,
     AppointmentRepository,
     { provide: BUSINESS_TOKEN, useClass: BusinessService },
     ApplicationModelService,
   ],
 })
 export class AppModule {}

我们来解读这段代码:

  • 第 9 行:[TypeOrmModule.forRoot(getDatabaseConfig()),] ——配置全局数据库连接——等价于原 Spring 项目中的 @Bean DataSource;
  • 第 10 行:[TypeOrmModule.forFeature([Doctor, Client, Slot, Appointment]),] ——声明 这个 模块中使用的实体,使它们的 Repository<T> 可以(通过 [@InjectRepository])注入到 src/repositories/ 中的类里。[User] 没有列在这里:由 [AuthModule] (第 11 行)声明它自己的 TypeOrmModule.forFeature([User])(见 auth/auth.module.ts);
  • 第 11 行:[AuthModule,] ——提供它自己的路由(POST /login)和自己的提供者(Passport 策略、JWT 守卫……)——一个完整的 [NestJS] 模块,而不是直接添加到 [AppModule] 中的文件,以使身份验证保持独立,便于移除或替换;
  • 第 21 行:[{ provide: BUSINESS_TOKEN, useClass: BusinessService },] ——[BusinessService] 以令牌 [BUSINESS_TOKEN] 注册,这样,任何请求 [IBusiness](通过 [@Inject]([BUSINESS_TOKEN]))的类都会收到 [BusinessService] 的一个实例——完全符合 Spring 接口注入的精神(@Autowired [IMetier] métier)。

4.9.7. .env.example

  PORT=8080

  DB_HOST=localhost
  DB_PORT=3306
  DB_USERNAME=root
  DB_PASSWORD=
  DB_DATABASE=dbrdvmedecins

  DB_SYNCHRONIZE=false

 JWT_SECRET=change-me-to-a-long-random-string
 JWT_EXPIRES_IN=2h

我们来解读这段代码:

  • 第 1 行:[PORT=8080] ——使用原 Spring Boot 服务器的端口;
  • 第 11–12 行:[JWT_SECRET=… / JWT_EXPIRES_IN=2h] ——身份验证引入的两个新变量:令牌签名的秘密密钥(在生产环境中必须更改——使用长的随机字符串,绝不要提交到版本库)及其有效期。

这个文件只是一个 示例:把它复制为 .env(绝不要提交它,因为它可能包含机密信息),然后根据您的机器调整其中的值。

4.10. 端到端验证

这一步使用大约十个 curl 场景,针对服务器的一个测试副本(内存数据库,预先填充了 admin/admin 和 user/user 两个账户)进行了验证:

  • 使用正确凭据的 POST /login 正确返回 { "status": 0, "data": { "accessToken": "...", "login": "admin", "name": "Administrator", "role": "ADMIN" } };
  • 使用错误密码的 POST /login 返回 401 Unauthorized([NestJS] 的原生 JSON 形式,而不是 [ServerResponse]<T> 信封);
  • 没有 Authorization 请求头的 GET /getAllDoctors 返回 401 Unauthorized 响应;
  • 带有效 JWT 令牌(admin 或 user)的 GET /getAllDoctors 正常返回医生列表,使用通常的 [ServerResponse]<T> 信封;
  • 带 admin 令牌的 POST /addAppointment 正常预约一个可用的时间段;
  • 带 user 令牌的 POST /addAppointment 返回 403 Forbidden 错误,消息说明角色 [USER] 不允许此操作(所需角色:ADMIN);
  • POST /deleteAppointment 的行为与 /addAppointment 对称,取决于所提交令牌的角色。