Menu
CoddyTech

截止日期

本课属于 Coddy Node.js 学习旅程的“REST API”单元。第 25 课,共 25 课。

任务会有截止日期,面板会显示哪些任务已逾期。不带时间的日期会以 ISO 字符串的形式传递,2026-03-15,zod 会用 z.iso.date() 检查:

z.iso.date().safeParse('2026-07-01').success   // true
z.iso.date().safeParse('2026-02-30').success   // false:不存在这一天
'2026-03-01' < '2026-03-15'                    // true

ISO 日期长度相同,并且年份在前,因此将它们作为字符串比较就能得到时间顺序。像 /overdue 这样的固定路径必须放在路由器中的 /:id 之前:Express 会按顺序尝试路由,而 /:id 会匹配任何单词。

challenge icon

挑战

简单

任务看板会显示哪些任务已逾期。为任务添加可选的截止日期,并添加一个逾期任务列表。

  1. 在 routes/tasks.js 中,为 Task 架构添加可选的 due 字段,并使用 z.iso.date() 进行检查。它只接受格式为 YYYY-MM-DD 的真实日期。"2026-03-15" 可以通过检查,而 "15/03/2026"、"2026-02-30" 和 "tomorrow" 会得到常见的 400 invalid_body 错误。确保 POST 会将 due 保存到新任务中。
  2. 向路由器添加 GET /api/v1/tasks/overdue。将它声明在 /:id 路由之前,否则 Express 会把 overdue 当作 ID 传给 /:id。
  3. 此路由从 ?today= 读取用于比较的日期,例如 ?today=2026-03-20。如果没有提供 today,就使用当前日期,并将其写成 YYYY-MM-DD 格式。若 today 不是一个真实日期,例如 ?today=soon,则会返回状态码 400:
    { "error": { "code": "invalid_query", "message": "today must be a date like 2026-03-10" } }
  4. 此路由返回任务数组,而不是列表路由返回的分页对象。任务同时满足以下三个条件时才算逾期:尚未完成、具有 due 日期,并且该日期早于 today。截止日期是 today 当天的任务还不算逾期。按 due 对数组排序,最早的日期排在前面。

试试看:在全新启动一次“运行”后,向 /api/v1/tasks 发送 POST 请求,依次提交 { "title": "Renew the lease", "due": "2026-03-15" } 和 { "title": "File the taxes", "due": "2026-03-01" }。两个请求都会返回 201,并包含各自的 due。然后,GET /api/v1/tasks/overdue?today=2026-03-20 会先返回截止日期较早的任务(你的 createdAt 时间会有所不同):

[
  { "id": 5, "title": "File the taxes", "done": false, "labels": [], "due": "2026-03-01", "createdAt": "2026-10-30T09:15:02.118Z" },
  { "id": 4, "title": "Renew the lease", "done": false, "labels": [], "due": "2026-03-15", "createdAt": "2026-10-30T09:14:40.006Z" }
]

GET /api/v1/tasks/overdue?today=2026-03-15 只会返回 "File the taxes"。GET /api/v1/tasks/overdue?today=soon 会返回 400,错误代码为 invalid_query。

亲手试试

import { Router } from 'express';
import { z } from 'zod';
import { config } from '../config.js';
import { sendError, sendInvalid } from '../errors.js';
import { nextId, tasks } from '../store.js';

const router = Router();

// 完整的任务,和 PUT 发送的内容一样。.strict() 会拒绝未列出的字段。
const Task = z
    .object({
        title: z.string().trim().min(1).max(100),
        done: z.boolean(),
        labels: z.array(z.string().trim().min(1).max(20)).max(5).optional(),
    })
    .strict();
const NewTask = Task.partial({ done: true });
const TaskChanges = Task.partial();
const SORT_FIELDS = ['title', 'createdAt'];

// 如果已有其他任务使用这个标题,无论大小写如何,结果都为 true。
const titleTaken = (title, exceptId) =>
    tasks.some((t) => t.id !== exceptId && t.title.toLowerCase() === title.toLowerCase());

router.get('/', (req, res) => {
    const { done, q, sort, label } = req.query;
    let list = tasks;
    if (done !== undefined) {
        if (done !== 'true' && done !== 'false') {
            return sendError(res, 400, 'invalid_query', 'done must be true or false');
        }
        list = list.filter((t) => t.done === (done === 'true'));
    }
    if (q !== undefined) {
        const words = String(q).toLowerCase();
        list = list.filter((t) => t.title.toLowerCase().includes(words));
    }
    if (label !== undefined) {
        list = list.filter((t) => t.labels.includes(String(label)));
    }
    if (sort !== undefined) {
        const field = String(sort).startsWith('-') ? String(sort).slice(1) : String(sort);
        if (!SORT_FIELDS.includes(field)) {
            return sendError(
                res,
                400,
                'invalid_query',
                'sort must be title or createdAt, with - in front to reverse',
            );
        }
        const direction = String(sort).startsWith('-') ? -1 : 1;
        list = list.toSorted((a, b) => a[field].localeCompare(b[field]) * direction);
    }
    const page = req.query.page === undefined ? 1 : Number(req.query.page);
    const limit = req.query.limit === undefined ? config.pageSize : Number(req.query.limit);
    if (!Number.isInteger(page) || page < 1) {
        return sendError(res, 400, 'invalid_query', 'page must be a whole number from 1');
    }
    if (!Number.isInteger(limit) || limit < 1 || limit > 50) {
        return sendError(res, 400, 'invalid_query', 'limit must be a whole number from 1 to 50');
    }
    const start = (page - 1) * limit;
    res.json({
        items: list.slice(start, start + limit),
        page,
        total: list.length,
        pages: Math.ceil(list.length / limit),
    });
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const result = NewTask.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { title, done = false, labels = [] } = result.data;
    if (titleTaken(title)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    const task = { id: nextId(), title, done, labels, createdAt: new Date().toISOString() };
    tasks.push(task);
    res.status(201).location(`/api/v1/tasks/${task.id}`).json(task);
});

router.patch('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = TaskChanges.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    if (result.data.title !== undefined && titleTaken(result.data.title, task.id)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    Object.assign(task, result.data);
    res.json(task);
});

router.put('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = Task.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { id, createdAt } = tasks[index];
    if (titleTaken(result.data.title, id)) {
        return sendError(res, 409, 'conflict', 'A task with this title already exists');
    }
    tasks[index] = { id, ...result.data, labels: result.data.labels ?? [], createdAt };
    res.json(tasks[index]);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;

REST API中的所有课

自己练习: Express 在线编辑器