Skip to content

8. RdvMedecins 服务器,一个黑盒

示例 22 至 25 以及随后的案例研究都与一个服务器交互:[RdvMedecins] 应用程序的 JSON 服务器。这是 [NestJS] 服务器,用于 [React]、[Vue.js]、[Angular] 和 [Flutter] 课程:即 [NestJS] 课程的服务器,其控制器不再生成 HTML 页面,而是生成 JSON 响应。这些讲义的读者已经熟悉本章内容,它在此几乎原样重现;他们只需查阅身份验证一节,其中解释了对于安装在手机上的 [Ionic] 应用程序有哪些变化。

在本课程中,这个服务器是一个黑盒:你不需要知道它是如何编写的。重要的只是它的 API——也就是它接受的 HTTP 请求列表以及它返回的响应。这是客户端开发人员的典型处境:API 是一份契约,服务器团队可以在该契约背后随意更改任何东西。为好奇的读者提供了它的源代码([rdvmedecins-nestjs-json] 文件夹),并附有大量注释。

本章说明如何安装服务器,描述它的 API,并使用 [curl] 查询它。

8.1. RdvMedecins 应用程序

该应用程序管理医疗诊所的预约。它有三种角色:

角色
对象
可以做什么
[ADMIN]
管理员([admin])
为所有患者安排和取消预约;管理医生和客户
[DOCTOR]
医生([pelissier]、[tatou]、[dupont])
为所有患者安排和取消预约;在日程中查看所有姓名
[USER]
患者([martin]、[durand]、[bistrou]、[german])
为自己预约;取消自己的预约;管理自己的账户。在日程中,他们看不到其他患者的姓名

演示账户使用其登录名作为密码。管理规则由服务器验证,与客户端无关:

  • 不得在过去的时间预约;
  • 每位患者只能有一个未来的预约;
  • 同一时间段在同一天只能被预约一次;
  • 两位医生(或两位客户)不能有相同的姓和名;一个登录名只属于一个账户;
  • 已有预约安排的医生不能被删除;
  • 已被他人在此期间修改的记录不能被覆盖(乐观锁);
  • 患者永远不会被分配到另一位患者的姓名。

8.2. 安装

你需要 [Node.js] (为 [Angular] 已经安装好;见第 2 章)以及一个 [MySQL] (或 [MariaDB])服务器:它们的安装在附录中描述。

1. 数据库。[database/dbrdvmedecins2.sql] 脚本会创建 [dbrdvmedecins2] 数据库、它的表以及示例数据。使用 [Laragon] 时,在 [HeidiSQL] 中运行它(File 菜单 / Run a SQL file);在命令行中:

mysql -u root -p < database/dbrdvmedecins2.sql

该脚本总是从一个空数据库开始:你可以重新运行它来恢复初始数据。

2. 库。在打开到 [rdvmedecins-nestjs-json] 文件夹的控制台窗口中:

npm install

3. 配置。把文件 [.env.example] 复制为 [.env] (在 [Windows] 下:[copy .env.example .env]),然后修改它:

# -----------------------------------------------------------------------
# 示例配置文件。
# 把这个文件复制为 [.env],然后根据你的机器调整其中的值。
# [.env] 文件绝不能共享或提交(其中有密码)。
# -----------------------------------------------------------------------

# JSON 服务器的监听端口
PORT=8080

# MySQL 数据库 [dbrdvmedecins2] 的连接参数
# (脚本:database/dbrdvmedecins2.sql)
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=
DB_DATABASE=dbrdvmedecins2
# true:在控制台中显示发送给 MySQL 的 SQL 查询
DB_LOGGING=false

# -----------------------------------------------------------------------
# 身份验证
# -----------------------------------------------------------------------
# 用于签署/验证 JWT 令牌的密钥——必须(MUST)修改
# 在生产环境中(一个较长的随机字符串,绝不提交)。
JWT_SECRET=change-me-to-a-long-random-string
# JWT 令牌的有效期,以秒为单位(7200 秒 = 2 小时)。携带该令牌的
# Cookie 具有相同的生存期。
JWT_EXPIRES_IN_SECONDS=7200
# 在生产环境中设为 true(站点通过 HTTPS 提供服务):这样身份验证
# Cookie 就永远不会通过未加密的连接发送。
COOKIE_SECURE=false

# -----------------------------------------------------------------------
# 防机器人保护
# -----------------------------------------------------------------------
# 登录:对于来自同一 IP 地址的同一登录名,允许的失败次数
# (验证码或密码错误),超过后这一组合就会被封锁……
LOGIN_MAX_FAILURES=5
# ……封锁这段时间(如果一个 IP 地址累计了
# 5 倍的失败次数(所有登录名合计),它也会被封锁)
LOGIN_BLOCK_MINUTES=15
# 客户账户创建:同一 IP 地址每小时最多创建的账户数量。
# 在教室里,所有电脑往往通过
# 同一个地址上网:如有需要,请调大该值。
REGISTRATION_MAX_PER_HOUR=10

# 验证码(CAPTCHA)测试模式:如果这个变量有值,该值就会
# 被接受为任何(ANY)验证码的答案。便于用 curl
# 查询 API(你无法在控制台中“读取”图片)。
# 在生产环境中请保持为空(EMPTY)。
CAPTCHA_TEST=

# -----------------------------------------------------------------------
# 生产环境
# -----------------------------------------------------------------------
# 已编译的 Web 客户端的文件夹,由该服务器提供服务(默认:client/)
# CLIENT_DIR=client
# 如果服务器位于代理(nginx……)之后,则设为 true
TRUST_PROXY=false
  • 第 8 行:服务器监听端口 8080;
  • 第 12–16 行:到 [MySQL] 的连接。使用 [Laragon] 时,用户 [root] 没有密码:默认值即可;
  • 第 25 行:用于签署身份验证令牌的密钥;
  • 第 38–45 行:反机器人措施:同一用户名在同一 IP 地址(IP)上连续 5 次登录失败后,该组合会被封锁 15 分钟;单个 IP 地址(IP)每小时最多只能创建 10 个账户。在应用程序开发期间——此时错误很常见——你可以在你的 [.env] 文件中调整这些值;
  • 第 51 行:验证码(CAPTCHA)测试模式。登录页面要求你重新输入图片中的字符,这在控制台中是不可能做到的。如果这个变量有值,该值就会被接受为任何验证码的答案,就像 [Google] 为其 [reCAPTCHA] 提供的“测试密钥”一样。对于本章中使用 [curl] 进行的测试,请输入 [CAPTCHA_TEST=test]。生成本课程截图的脚本也使用这个值。在生产环境中请将其留空;
  • 第 57–59 行:两项用于生产环境的设置(见“部署”一章)。

4. 启动。

npm run start:dev

控制台显示(节选;[start:dev] 会在每次修改服务器代码时重新启动它):

[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [NestFactory] Starting Nest application...
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +19ms
...
[Nest] 13189  - 10/06/2026, 1:29:56 PM    WARN [RdvMedecins] captcha TEST MODE active (CAPTCHA_TEST in .env): never use it in production
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [RoutesResolver] ScheduleController {/api/schedule}: +1ms
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [RouterExplorer] Mapped {/api/schedule, GET} route +1ms
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [RoutesResolver] AppointmentsController {/api/appointments}: +0ms
...
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [RouterExplorer] Mapped {/api/auth/me, GET} route +0ms
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [NestApplication] Nest application successfully started +6ms
[Nest] 13189  - 10/06/2026, 1:29:56 PM     LOG [RdvMedecins] JSON server started: http://localhost:8080/api

每一行 [Mapped] 都宣告了 API 的一个路由。如果数据库无法访问([MySQL] 服务器已停止、密码错误),服务器会立即停止,并给出连接错误消息。

8.3. 响应格式

所有路由都以 [/api] 开头。成功的请求会收到 2xx 状态码,并在响应体中以 JSON 格式返回所请求的数据。被拒绝的请求会收到 4xx 或 5xx 状态码,并在响应体中以相同的格式返回数据:

1
2
3
4
5
6
{
  "statusCode": 400,
  "key": "ERRORS.INVALID_FORM",
  "params": { "min": "6" },
  "fields": { "lastName": "ERRORS.LASTNAME_REQUIRED", "password": "ERRORS.PASSWORD_TOO_SHORT" }
}
  • [statusCode]:HTTP 代码,在响应体中重复出现;
  • [key]:消息的翻译键。服务器从不返回要显示的文本:它不知道用户的语言。由客户端使用它的字典来翻译该键(见示例 21);
  • [params] (可选):消息参数(“At least {{min}} characters”、“Please try again in {{minutes}} minute(s)”);
  • [fields] (可选):对于被拒绝的表单,每个字段的错误。

所使用的代码:

代码
含义
键的示例
400
无效请求
[ERRORS.INVALID_FORM] (+ fields)、[ERRORS.INVALID_DATE]、[ERRORS.WRONG_CAPTCHA]、[ERRORS.CHOOSE_PATIENT]、[ERRORS.WRONG_CURRENT_PASSWORD]、[ERRORS.BAD_REQUEST]……
401
未通过身份验证
[ERRORS.AUTH_REQUIRED] (没有令牌)、[ERRORS.SESSION_EXPIRED] (令牌无效或已过期)、[LOGIN.ERROR]
403
拒绝访问
[ERRORS.FORBIDDEN] (角色不足)、[ERRORS.CAPTCHA_BEFORE_ACCOUNT] (没有通行证)
404
未找到
[ERRORS.NOT_FOUND]、[ERRORS.DOCTOR_NOT_FOUND]、[ERRORS.APPOINTMENT_NOT_FOUND]……
409
违反业务规则
[ERRORS.PAST_DATE]、[ERRORS.SLOT_ALREADY_BOOKED]、[ERRORS.LOGIN_TAKEN]、[ERRORS.CONCURRENT_UPDATE]……
415
非 JSON 的 POST 请求
[ERRORS.JSON_REQUIRED]
429
尝试次数过多
[ERRORS.TOO_MANY_ATTEMPTS]、[ERRORS.TOO_MANY_ACCOUNTS] (+ params.minutes)
500
服务器错误
[ERRORS.SERVER_ERROR]

8.4. 身份验证

客户端使用 [POST /api/auth/login] 进行身份验证,提交用户名、密码和验证码答案。作为回应,服务器在其响应的 [Set-Cookie] 头中发送一个包含已签名 JWT 令牌的 Cookie:

Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; Expires=Tue, 06 Oct 2026 14:12:15 GMT; HttpOnly; SameSite=Strict

此后,客户端必须在每个请求的 [Cookie] 头中带上这个 Cookie,这些请求发往 [/api]:服务器就是这样知道是谁在发出请求的。

这个服务器是为 Web 客户端设计的,它的设计选择由 Web 浏览器特有的风险所驱动:

  • [HttpOnly]:页面上的 [JavaScript] 代码无法读取这个 Cookie。因此,注入页面的恶意脚本无法窃取令牌。对客户端的影响:它无法自行判断自己是否已登录。它需要询问服务器([GET /api/auth/me]);
  • [Path=/api]:该 Cookie 只会包含在发往 API 的请求中;
  • [SameSite=Strict]:浏览器只会在发往本站页面的请求中包含该 Cookie。另一个站点上的恶意页面无法让浏览器以用户的名义执行操作(即所谓的 CSRF 攻击);
  • [Max-Age=7200]:它在两小时后过期,与令牌过期的时间相同。

针对 CSRF 攻击的第二道防线:服务器会拒绝(415)任何请求体不是 JSON 的 POST 请求。另一个站点上被入侵的 HTML 表单无法发送 JSON。

8.4.1. 移动客户端有哪些变化

[Ionic] 应用是一个由“WebView”(来自 [Chrome] 的浏览器引擎,位于 [Android] 上)在手机上运行的 Web 应用:它遵循与浏览器相同的规则吗?在本课程中,我们需要区分它的两种运行方式。

在电脑的浏览器中,开发期间([ng serve])。应用程序由 [Angular] 开发服务器(http://localhost:8100)提供;JSON 服务器位于另一个端口(8080)。这是两个不同的源,浏览器会应用两条有问题的规则:除非服务器授权(即“CORS”机制,我们的服务器不支持),否则它不会接受来自不同源的响应;并且它不会在“来自另一个站点”的请求中包含 [SameSite=Strict] Cookie。解决办法与 [React] 和 [Vue.js] 课程中相同:使用代理。开发服务器会把所有地址以 [/api] 开头的请求转发给 JSON 服务器(文件 [proxy.conf.json],见示例 22)。从浏览器的角度看,应用程序和 API 具有相同的源:浏览器会存储该 Cookie 并把它发回,而应用程序代码无需做任何事情。

在手机上 ([Android]、[Capacitor])。页面由 [Capacitor] 自身从地址 https://localhost 提供;JSON 服务器在电脑上,地址类似 http://10.0.2.2:8080(见示例 22)。同样,这里也有两个源。项目启用了 [CapacitorHttp] 插件,来自 [Capacitor] (文件 [capacitor.config.ts]):应用程序的 HTTP 请求不再由 WebView 发送,而是由 [Android] 的原生代码发送。其影响如下:

  • 不再有 CORS 检查:这项检查是浏览器的规则,而原生代码不是浏览器([curl] 也不是);
  • 收到的 Cookie 由 [Android] 存储(它的 Cookie 管理器,与 WebView 的相同),并在之后发往同一服务器的请求中自动带回。它们保留在设备上:关闭再重新打开应用后,你仍然处于登录状态;
  • [HttpOnly] 和 [SameSite] 属性不会造成任何问题:应用程序代码从不读取该 Cookie(它通过 [GET /api/auth/me] 询问谁已登录),而且请求也不是由“来自另一个站点”的页面发出的。

这与 [Flutter] 课程有一个重要区别:[Flutter] 应用没有浏览器,必须编写自己的 HTTP 客户端,在响应中读取 [Set-Cookie] 头,并在请求中写入 [Cookie] 头。而使用 [Ionic] 时,无论是在浏览器中还是在手机上,Cookie 都会被自动传递,无需一行代码。而服务器这边无需做任何改动:它看到的只是普通的 HTTP 请求,其中包含它设置的 Cookie。

8.5. API

方法
地址
角色
发送内容/响应体
GET
[/api/captcha]
公开
响应:[{ id, svg }]
POST
[/api/auth/login]
公开
[{ login, password, captchaId, captcha }];响应:[{ login, name, role }] + Cookie
POST
[/api/auth/logout]
公开
[{}] ;删除 Cookie
GET
[/api/auth/me]
已登录
响应:[{ login, name, role }]
GET
[/api/schedule?doctorId=&day=]
所有角色
响应:日程(不带 doctorId 时:对于 DOCTOR,是他自己的日程)
POST
[/api/appointments]
所有角色
[{ day, slotId, clientId }](对于 USER,clientId 被忽略);201
DELETE
[/api/appointments/:id]
所有角色
USER 只能取消自己的预约
GET
[/api/doctors]
所有角色
列表(对 ADMIN 附带登录名)
GET
[/api/clients]
ADMIN, DOCTOR
列表(对 ADMIN 附带登录名)
GET
[/api/doctors/:id]、[/api/clients/:id]
ADMIN
一条记录
POST
[/api/doctors]、[/api/clients]
ADMIN
[{ title, firstName, lastName, login?, password? }];201
PUT
[/api/doctors/:id]、[/api/clients/:id]
ADMIN
[{ title, firstName, lastName, login?, password?, version }]
DELETE
[/api/doctors/:id]、[/api/clients/:id]
ADMIN
响应:[{}]
POST
[/api/register/access]
公开
[{ captchaId, captcha }];签发一个令牌(Cookie)
GET
[/api/register/access]
公开
响应:[{ valid }]
POST
[/api/register]
公开 + 通行证
[{ title, firstName, lastName, login, password, confirmation }];201
GET
[/api/my-area]
USER
响应:[{ patient, appointments }]
GET
[/api/my-account]
USER
响应:[{ title, firstName, lastName, login, version }]
PUT
[/api/my-account]
USER
[{ title, firstName, lastName, login, password?, confirmation?, currentPassword, version }]
DELETE
[/api/my-account]
USER
[{ currentPassword }];删除账户及其预约

日程条目([GET /api/schedule])描述一个时间段,以及已登录用户被授权对它做什么:

1
2
3
4
{ "id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0,
  "free": false,
  "patient": { "title": "Mme", "firstName": "Alice", "lastName": "DURAND" },
  "mine": false, "bookable": false, "appointmentId": 2 }
  • [free]:该时间段在那一天是否可用?
  • [patient]:该预约的患者。对于已登录的患者,它等于 [null], 除了他自己的(预约):其他患者的姓名从不发送;
  • [mine]:这是已登录患者自己的预约;
  • [bookable]:用户能否预约该时间段(可用、不在过去,并且对于患者而言没有未来的预约)?
  • [appointmentId]:如果用户可以取消该预约,则会填写它。

服务器负责决定;客户端负责显示。即使客户端作弊(在不该显示的时候显示“预约”按钮),服务器在预约时也会再次核实一切。

8.6. 使用 curl 查询 API

服务器上的 [curl] 文件夹包含本章各请求的 JSON 请求体,每个请求一个文件。例如 [curl/login-admin.json]:

{ "login": "admin", "password": "admin", "captchaId": "-", "captcha": "test" }

这些命令在打开到 [rdvmedecins-nestjs-json] 目录的控制台中输入,服务器以验证码测试模式([CAPTCHA_TEST=test])运行,数据库刚刚(重新)初始化过。[curl] 的一些选项:

  • [-i]:同时显示响应头;[-s]:不显示进度条;
  • [--json @file]:以 POST 发送文件的内容,并带有头 [Content-Type: application/json] ([curl] 7.82 及更高版本;对于较旧的版本,使用 [-H "Content-Type: application/json" -d @file]);
  • [-X PUT]、[-X DELETE]:HTTP 方法;
  • [-c cookies.txt]:把收到的 Cookie 保存到这个文件中;[-b cookies.txt]:把它们发送回去。[curl] 就是这样在各条命令之间“保持登录”的,就像浏览器那样。

在 [PowerShell] 下,必须输入 [curl.exe] 而不是 [curl] (后者指的是另一个命令)。以下输出来自一次真实的会话(2026 年 10 月 6 日,预约安排在 2030 年 1 月,因此它们仍然在未来)。篇幅较长的 JSON 响应已为本文档做了格式化(每个对象一行),JWT 令牌和验证码图片已被截断(“...”),并且已删除头 [Date]、[ETag]、[Connection] 和 [Keep-Alive] 。

8.6.1. 登录

首先是验证码(图片已被截断):

1
2
3
4
5
6
7
$ curl -i http://localhost:8080/api/captcha
HTTP/1.1 200 OK
Cache-Control: no-store
Content-Type: application/json; charset=utf-8
Content-Length: 13195

{"id":"8f711d55-566c-44e6-b02b-f114a02279f6","svg":"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"150..."}

没有令牌时,受保护的 URL 会返回 401 响应:

1
2
3
4
5
6
$ curl -i http://localhost:8080/api/doctors
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 47

{"statusCode":401,"key":"ERRORS.AUTH_REQUIRED"}

先是错误的验证码,再是错误的密码:

1
2
3
4
5
6
$ curl -i --json @curl/login-wrong-captcha.json http://localhost:8080/api/auth/login
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 91

{"statusCode":400,"key":"ERRORS.WRONG_CAPTCHA","fields":{"captcha":"ERRORS.WRONG_CAPTCHA"}}
1
2
3
4
5
6
$ curl -i --json @curl/login-wrong-password.json http://localhost:8080/api/auth/login
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 38

{"statusCode":401,"key":"LOGIN.ERROR"}

登录成功会设置 Cookie,[curl] 把它存储在 [cookies.txt] 中:

1
2
3
4
5
6
7
$ curl -i -c cookies.txt --json @curl/login-admin.json http://localhost:8080/api/auth/login
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; Expires=Tue, 06 Oct 2026 14:12:15 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 55

{"login":"admin","name":"Administrator","role":"ADMIN"}

有了这个 Cookie,服务器就知道我们是谁:

1
2
3
4
5
6
$ curl -i -b cookies.txt http://localhost:8080/api/auth/me
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 55

{"login":"admin","name":"Administrator","role":"ADMIN"}

伪造的(或已过期的)令牌会导致会话过期,并且服务器会要求删除该 Cookie(一个已过期的到期日期):

1
2
3
4
5
6
7
$ curl -i -b "rdvmedecins_jwt=abc.def.ghi" http://localhost:8080/api/auth/me
HTTP/1.1 401 Unauthorized
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 49

{"statusCode":401,"key":"ERRORS.SESSION_EXPIRED"}

8.6.2. 医生、客户、日程

医生列表,从 ADMIN 的视角看(带登录名):

$ curl -i -b cookies.txt http://localhost:8080/api/doctors
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 282

[
  {"id":3,"version":0,"title":"Melle","firstName":"Sophie","lastName":"DUPONT","login":"dupont"},
  {"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER","login":"pelissier"},
  {"id":2,"version":0,"title":"Mr","firstName":"Paul","lastName":"TATOU","login":"tatou"}
]

PELISSIER 医生 2030 年 1 月 15 日的日程:

$ curl -s -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
  "doctor":{"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER"},
  "day":"2030-01-15",
  "slots":[
    {"id":1,"startHour":8,"startMinute":0,"endHour":8,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":2,"startHour":8,"startMinute":20,"endHour":8,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":3,"startHour":8,"startMinute":40,"endHour":9,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":4,"startHour":9,"startMinute":0,"endHour":9,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":5,"startHour":9,"startMinute":20,"endHour":9,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":6,"startHour":9,"startMinute":40,"endHour":10,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":7,"startHour":10,"startMinute":0,"endHour":10,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":8,"startHour":10,"startMinute":20,"endHour":10,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":9,"startHour":10,"startMinute":40,"endHour":11,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":10,"startHour":11,"startMinute":0,"endHour":11,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":11,"startHour":11,"startMinute":20,"endHour":11,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":12,"startHour":11,"startMinute":40,"endHour":12,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null}
  ],
  "info":null
}

一个不存在的日期:

1
2
3
4
5
6
$ curl -i -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-02-30"
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 46

{"statusCode":400,"key":"ERRORS.INVALID_DATE"}

8.6.3. 预约

ADMIN 为 2 号患者(Alice DURAND)预约第 3 个时间段。请求体([curl/appointment-admin.json]):

{ "day": "2030-01-15", "slotId": 3, "clientId": 2 }
1
2
3
4
5
6
$ curl -i -b cookies.txt --json @curl/appointment-admin.json http://localhost:8080/api/appointments
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 51

{"id":2,"day":"2030-01-15","slotId":3,"clientId":2}

日程现在显示了这个预约,以及患者的姓名和如何取消它的说明([appointmentId]):

$ curl -s -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
  "doctor":{"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER"},
  "day":"2030-01-15",
  "slots":[
    {"id":1,"startHour":8,"startMinute":0,"endHour":8,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":2,"startHour":8,"startMinute":20,"endHour":8,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":3,"startHour":8,"startMinute":40,"endHour":9,"endMinute":0,"free":false,"patient":{"title":"Mme","firstName":"Alice","lastName":"DURAND"},"mine":false,"bookable":false,"appointmentId":2},
    {"id":4,"startHour":9,"startMinute":0,"endHour":9,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":5,"startHour":9,"startMinute":20,"endHour":9,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":6,"startHour":9,"startMinute":40,"endHour":10,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":7,"startHour":10,"startMinute":0,"endHour":10,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":8,"startHour":10,"startMinute":20,"endHour":10,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":9,"startHour":10,"startMinute":40,"endHour":11,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":10,"startHour":11,"startMinute":0,"endHour":11,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":11,"startHour":11,"startMinute":20,"endHour":11,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":12,"startHour":11,"startMinute":40,"endHour":12,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null}
  ],
  "info":null
}

再试一次:该患者已经有一个未来的预约。过去的预约(2020 年 1 月 15 日,文件 [curl/appointment-past.json])同样会被拒绝:

1
2
3
4
5
6
$ curl -i -b cookies.txt --json @curl/appointment-admin.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 66

{"statusCode":409,"key":"ERRORS.PATIENT_HAS_UPCOMING_APPOINTMENT"}
1
2
3
4
5
6
$ curl -i -b cookies.txt --json @curl/appointment-past.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 43

{"statusCode":409,"key":"ERRORS.PAST_DATE"}

标准的 HTML 表单(这里用 [-d] 模拟,它发送 [application/x-www-form-urlencoded])会被拒绝:

1
2
3
4
5
6
$ curl -i -b cookies.txt -d "day=2030-01-15&slotId=4&clientId=2" http://localhost:8080/api/appointments
HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json; charset=utf-8
Content-Length: 47

{"statusCode":415,"key":"ERRORS.JSON_REQUIRED"}

8.6.4. 患者的视角

你先退出登录,然后以 [martin] 登录:

1
2
3
4
5
6
7
$ curl -i -b cookies.txt -c cookies.txt --json @curl/empty.json http://localhost:8080/api/auth/logout
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2

{}
$ curl -s -c cookies-martin.txt --json @curl/login-martin.json http://localhost:8080/api/auth/login
{"login":"martin","name":"Jean MARTIN","role":"USER"}

同一个日程,从患者的视角看:第 3 个时间段已被占用(["free":false]),但 ["patient"] 等于 [null]:Alice 的姓名(DURAND)没有被发送:

$ curl -s -b cookies-martin.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
  "doctor":{"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER"},
  "day":"2030-01-15",
  "slots":[
    {"id":1,"startHour":8,"startMinute":0,"endHour":8,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":2,"startHour":8,"startMinute":20,"endHour":8,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":3,"startHour":8,"startMinute":40,"endHour":9,"endMinute":0,"free":false,"patient":null,"mine":false,"bookable":false,"appointmentId":null},
    {"id":4,"startHour":9,"startMinute":0,"endHour":9,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":5,"startHour":9,"startMinute":20,"endHour":9,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":6,"startHour":9,"startMinute":40,"endHour":10,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":7,"startHour":10,"startMinute":0,"endHour":10,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":8,"startHour":10,"startMinute":20,"endHour":10,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":9,"startHour":10,"startMinute":40,"endHour":11,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":10,"startHour":11,"startMinute":0,"endHour":11,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":11,"startHour":11,"startMinute":20,"endHour":11,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":12,"startHour":11,"startMinute":40,"endHour":12,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null}
  ],
  "info":null
}

患者无权访问客户列表:

1
2
3
4
5
6
$ curl -i -b cookies-martin.txt http://localhost:8080/api/clients
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 43

{"statusCode":403,"key":"ERRORS.FORBIDDEN"}

他为自己预约(记录 [curl/appointment-martin.json] 不包含 [clientId]),一次成功,第二次不行([curl/appointment-martin-2.json]:第二天,第 6 个时间段):

{ "day": "2030-01-15", "slotId": 5 }
1
2
3
4
5
6
$ curl -i -b cookies-martin.txt --json @curl/appointment-martin.json http://localhost:8080/api/appointments
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 51

{"id":3,"day":"2030-01-15","slotId":5,"clientId":1}
1
2
3
4
5
6
$ curl -i -b cookies-martin.txt --json @curl/appointment-martin-2.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 55

{"statusCode":409,"key":"SCHEDULE.ALREADY_BOOKED_INFO"}

他的专属区域:

$ curl -s -b cookies-martin.txt http://localhost:8080/api/my-area
{
  "patient":{"title":"Mr","firstName":"Jean","lastName":"MARTIN"},
  "appointments":[
    {
      "id":3,
      "day":"2030-01-15",
      "slot":{"id":5,"startHour":9,"startMinute":20,"endHour":9,"endMinute":40},
      "doctor":{"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER"}
    }
  ]
}

他不能取消另一位患者的预约。服务器会回应“未找到”,就像对不存在的预约那样:它不会泄露任何关于其他患者预约的信息:

1
2
3
4
5
6
$ curl -i -b cookies-martin.txt -X DELETE http://localhost:8080/api/appointments/2
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Content-Length: 55

{"statusCode":404,"key":"ERRORS.APPOINTMENT_NOT_FOUND"}

取消他自己的预约则可以:

1
2
3
4
5
6
$ curl -i -b cookies-martin.txt -X DELETE http://localhost:8080/api/appointments/3
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 2

{}

8.6.5. 医生的视角

PELISSIER 医生登录:

$ curl -s -c cookies-pelissier.txt --json @curl/login-pelissier.json http://localhost:8080/api/auth/login
{"login":"pelissier","name":"Marie PELISSIER","role":"DOCTOR"}

没有 [doctorId] 时,已登录的医生会收到他自己的(OWN)日程,带有所有姓名([martin]的预约刚刚被取消:Alice 的预约(DURAND)仍然保留):

$ curl -s -b cookies-pelissier.txt "http://localhost:8080/api/schedule?day=2030-01-15"
{
  "doctor":{"id":1,"version":0,"title":"Mme","firstName":"Marie","lastName":"PELISSIER"},
  "day":"2030-01-15",
  "slots":[
    {"id":1,"startHour":8,"startMinute":0,"endHour":8,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":2,"startHour":8,"startMinute":20,"endHour":8,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":3,"startHour":8,"startMinute":40,"endHour":9,"endMinute":0,"free":false,"patient":{"title":"Mme","firstName":"Alice","lastName":"DURAND"},"mine":false,"bookable":false,"appointmentId":2},
    {"id":4,"startHour":9,"startMinute":0,"endHour":9,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":5,"startHour":9,"startMinute":20,"endHour":9,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":6,"startHour":9,"startMinute":40,"endHour":10,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":7,"startHour":10,"startMinute":0,"endHour":10,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":8,"startHour":10,"startMinute":20,"endHour":10,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":9,"startHour":10,"startMinute":40,"endHour":11,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":10,"startHour":11,"startMinute":0,"endHour":11,"endMinute":20,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":11,"startHour":11,"startMinute":20,"endHour":11,"endMinute":40,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null},
    {"id":12,"startHour":11,"startMinute":40,"endHour":12,"endMinute":0,"free":true,"patient":null,"mine":false,"bookable":true,"appointmentId":null}
  ],
  "info":null
}

它不处理医生:

1
2
3
4
5
6
$ curl -i -b cookies-pelissier.txt --json @curl/doctor-add.json http://localhost:8080/api/doctors
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 43

{"statusCode":403,"key":"ERRORS.FORBIDDEN"}

8.6.6. 管理医生和客户(ADMIN)

ADMIN 重新登录(之前它已退出):

$ curl -s -c cookies.txt --json @curl/login-admin.json http://localhost:8080/api/auth/login
{"login":"admin","name":"Administrator","role":"ADMIN"}

新增。如果缺少登录名,则默认使用小写的姓名;密码即登录名([curl/doctor-add.json]):

{ "title": "Mme", "firstName": "Claire", "lastName": "LEROY" }
1
2
3
4
5
6
$ curl -i -b cookies.txt --json @curl/doctor-add.json http://localhost:8080/api/doctors
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 90

{"id":4,"version":1,"title":"Mme","firstName":"Claire","lastName":"LEROY","login":"leroy"}

无效的请求体:响应列出每个字段的错误([curl/doctor-invalid.json]):

{ "title": "Dr", "firstName": "", "lastName": "A-LAST-NAME-FAR-TOO-LONG-FOR-THE-DB", "login": "Claire L" }
$ curl -i -b cookies.txt --json @curl/doctor-invalid.json http://localhost:8080/api/doctors
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 218

{
  "statusCode":400,
  "key":"ERRORS.INVALID_FORM",
  "params":{"min":"6"},
  "fields":{"login":"ERRORS.INVALID_LOGIN","title":"ERRORS.INVALID_TITLE","firstName":"ERRORS.FIRSTNAME_REQUIRED","lastName":"ERRORS.LASTNAME_TOO_LONG"}
}

同名者(Paul TATOU 先生,[curl/doctor-duplicate.json]):两个受影响的字段都会被标出:

$ curl -i -b cookies.txt --json @curl/doctor-duplicate.json http://localhost:8080/api/doctors
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 151

{
  "statusCode":409,
  "key":"ERRORS.DOCTOR_ALREADY_EXISTS",
  "fields":{"firstName":"ERRORS.DOCTOR_ALREADY_EXISTS","lastName":"ERRORS.DOCTOR_ALREADY_EXISTS"}
}

修改。[version] 是随记录一起读取的版本(这里是 1,[curl/doctor-edit.json]):

{ "title": "Mme", "firstName": "Claire", "lastName": "LEROY-MARTIN", "version": 1 }
1
2
3
4
5
6
$ curl -i -b cookies.txt -X PUT --json @curl/doctor-edit.json http://localhost:8080/api/doctors/4
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 97

{"id":4,"version":2,"title":"Mme","firstName":"Claire","lastName":"LEROY-MARTIN","login":"leroy"}

该记录现在是版本 2。再次提交同一修改(带着版本 1)会覆盖一条此后已被他人修改的记录:这正是乐观锁所阻止的:

1
2
3
4
5
6
$ curl -i -b cookies.txt -X PUT --json @curl/doctor-edit.json http://localhost:8080/api/doctors/4
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 51

{"statusCode":409,"key":"ERRORS.CONCURRENT_UPDATE"}

已有预约的医生不能被删除;其他医生可以:

1
2
3
4
5
6
$ curl -i -b cookies.txt -X DELETE http://localhost:8080/api/doctors/1
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 57

{"statusCode":409,"key":"ERRORS.DOCTOR_HAS_APPOINTMENTS"}
1
2
3
4
5
6
$ curl -i -b cookies.txt -X DELETE http://localhost:8080/api/doctors/4
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 2

{}

8.6.7. 创建账户

没有通行证,就不可能:

1
2
3
4
5
6
$ curl -i --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 56

{"statusCode":403,"key":"ERRORS.CAPTCHA_BEFORE_ACCOUNT"}

首先,你要解答一个验证码([curl/captcha-test.json]:[{ "captchaId": "-", "captcha": "test" }]);服务器在一个 Cookie 中签发一个有效期为 15 分钟的令牌:

1
2
3
4
5
6
7
$ curl -i -c cookies-registration.txt --json @curl/captcha-test.json http://localhost:8080/api/register/access
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_registration=d2f6290a-b277-4785-9fd9-fada3be36087; Max-Age=900; Path=/api/register; Expires=Tue, 06 Oct 2026 12:27:16 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 2

{}
$ curl -s -b cookies-registration.txt http://localhost:8080/api/register/access
{"valid":true}

密码确认必须一致([curl/registration-confirmation.json]:“secret1”,然后是“secret2”):

1
2
3
4
5
6
$ curl -i -b cookies-registration.txt --json @curl/registration-confirmation.json http://localhost:8080/api/register
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 98

{"statusCode":400,"key":"ERRORS.INVALID_FORM","fields":{"confirmation":"ERRORS.PASSWORDS_DIFFER"}}

正确的请求体([curl/registration.json]):

{ "title": "Mme", "firstName": "Julie", "lastName": "BERNARD", "login": "jbernard", "password": "secret1", "confirmation": "secret1" }
1
2
3
4
5
6
7
$ curl -i -b cookies-registration.txt -c cookies-registration.txt --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 201 Created
Set-Cookie: rdvmedecins_registration=; Path=/api/register; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 20

{"login":"jbernard"}

通行证已被使用:它不能用来创建第二个账户:

1
2
3
4
5
6
$ curl -i -b cookies-registration.txt --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 56

{"statusCode":403,"key":"ERRORS.CAPTCHA_BEFORE_ACCOUNT"}

8.6.8. 管理你的账户

新患者登录并读取她的记录:

$ curl -s -c cookies-jbernard.txt --json @curl/login-jbernard.json http://localhost:8080/api/auth/login
{"login":"jbernard","name":"Julie BERNARD","role":"USER"}
$ curl -s -b cookies-jbernard.txt http://localhost:8080/api/my-account
{"title":"Mme","firstName":"Julie","lastName":"BERNARD","login":"jbernard","version":1}

修改需要当前密码。服务器会签发一个新令牌,其中包含新的姓名([curl/my-account.json]):

{ "title": "Mme", "firstName": "Julie", "lastName": "BERNARD-DUVAL", "login": "jbernard", "currentPassword": "secret1", "version": 1 }
1
2
3
4
5
6
7
$ curl -i -b cookies-jbernard.txt -c cookies-jbernard.txt -X PUT --json @curl/my-account.json http://localhost:8080/api/my-account
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; Expires=Tue, 06 Oct 2026 14:12:17 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 63

{"login":"jbernard","name":"Julie BERNARD-DUVAL","role":"USER"}

删除账户([curl/my-account-delete.json]: [{ "currentPassword": "secret1" }])同样会删除 Cookie:

1
2
3
4
5
6
7
$ curl -i -b cookies-jbernard.txt -c cookies-jbernard.txt -X DELETE --json @curl/my-account-delete.json http://localhost:8080/api/my-account
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2

{}
1
2
3
4
5
6
$ curl -i -b cookies-jbernard.txt http://localhost:8080/api/auth/me
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 47

{"statusCode":401,"key":"ERRORS.AUTH_REQUIRED"}

8.6.9. 一些错误

一个未知的路由,一个不是有效 JSON 的请求体:

1
2
3
4
5
6
$ curl -i -b cookies-martin.txt http://localhost:8080/api/does-not-exist
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Content-Length: 43

{"statusCode":404,"key":"ERRORS.NOT_FOUND"}
1
2
3
4
5
6
$ curl -i -b cookies.txt -H "Content-Type: application/json" -d "{not json" http://localhost:8080/api/appointments
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 45

{"statusCode":400,"key":"ERRORS.BAD_REQUEST"}

现在,对于编写我们的客户端所需了解的有关服务器的一切,我们都已经知道了。