期限
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' // trueISO日付はすべて同じ長さで、年が先に来るため、文字列として比較すると時系列順になります。/overdue のような固定パスは、ルーター内で /:id より前に置く必要があります。Expressはルートを順番に試し、/:id は任意の単語に一致するためです。
チャレンジ
簡単ボードには期限を過ぎたタスクが表示されます。タスクに任意の期限日を追加し、期限を過ぎたタスクの一覧を追加しましょう。
routes/tasks.jsで、Taskスキーマに任意のdueフィールドを追加し、z.iso.date()で検証します。受け入れられるのは、YYYY-MM-DD形式で記述された実在の日付だけです。"2026-03-15"は有効ですが、"15/03/2026"、"2026-02-30"、"tomorrow"は通常の400invalid_bodyエラーになります。POSTで新しいタスクにdueが保存されるようにしてください。- ルーターに
GET /api/v1/tasks/overdueを追加します。このルートは/:idルートより上に宣言してください。そうしないと、Expressはoverdueを/:idのIDとして扱います。 - このルートは、比較に使う日付を
?today=から読み取ります。たとえば?today=2026-03-20です。todayが指定されていない場合は、現在の日付をYYYY-MM-DD形式で使用します。?today=soonのように、実在の日付ではないtodayが指定されると、ステータス400が返ります:{ "error": { "code": "invalid_query", "message": "today must be a date like 2026-03-10" } } - このルートは、一覧が返すページオブジェクトではなく、タスクの配列をそのまま返します。次の3つすべてに当てはまるタスクは期限超過です。未完了であること、
dueの日付があること、その日付がtodayより前であることです。期限日がtoday当日のタスクは、まだ期限超過ではありません。配列をdueで並べ替え、最も早い日付を先頭にしてください。
試してみましょう:新しいRunで、まず{ "title": "Renew the lease", "due": "2026-03-15" }をPOSTし、続けて{ "title": "File the taxes", "due": "2026-03-01" }を/api/v1/tasksにPOSTします。どちらもdueを含めて201を返します。次に、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は、コードinvalid_queryとともに400を返します。
自分で試してみよう
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プレイグラウンド