機能追加(ノート)
顧客管理アプリを友人に見せたところ、次のような要望をもらいました。
顧客ごとに、打ち合わせの内容などのメモを残したい
この要望に応えるために、顧客ごとにノートを書けるようにします。
前の節を終えていない人は、ここから始められます。api で npm install と npm run db:init、client で npm install を実行してから始めてください。
データを考える
Section titled “データを考える”1 人の顧客に、たくさんのノートが付きます(1 対多)。ノートには、どの顧客のノートかを表す customerId を持たせます。
erDiagram
customer["顧客"] {
int id "顧客ID"
string name "名前"
string email "メールアドレス"
string tel "電話番号"
string address "住所"
}
note["🆕 ノート"] {
int id "ノートID"
string body "本文"
string createdAt "書いた日時"
int customerId "顧客ID"
}
customer ||--o{ note : "1対多"
機能と Web API を考える
Section titled “機能と Web API を考える”ノートは顧客の詳細の画面の中に表示し、その場で追加・削除できるようにします。
graph LR A[顧客一覧] --> B["顧客詳細<br>🆕 ノートの一覧・追加・削除"] A --> C[顧客作成]
| 機能 | クライアントの関数 | Web API |
|---|---|---|
| 🆕 顧客のノート一覧表示 | getNotes(customerId) |
GET /customers/:id/notes |
| 🆕 ノート作成 | createNote(customerId, note) |
POST /customers/:id/notes |
| 🆕 ノート削除 | deleteNote(id) |
DELETE /notes/:id |
「ある顧客のノート」の一覧と作成は、/customers/:id/notes のように顧客のパスの下に置きます。どの顧客のノートかがパスから分かります。一方、削除は ID だけでノートが決まるので、/notes/:id にします。
データベースを変える
Section titled “データベースを変える”note テーブルを足します。
api/db/init.sql を変更する
Section titled “api/db/init.sql を変更する”1DROP TABLE IF EXISTS note;12DROP TABLE IF EXISTS customer;23
34CREATE TABLE customer (89 address TEXT NOT NULL DEFAULT ''910);1011
12CREATE TABLE note (13 id INTEGER PRIMARY KEY AUTOINCREMENT,14 body TEXT NOT NULL,15 created_at TEXT NOT NULL,16 customer_id INTEGER NOT NULL REFERENCES customer(id) ON DELETE CASCADE17);18
1119INSERT INTO customer (name, email, tel, address) VALUES1220 ('山田太郎', 'taro@yamada.example', '03-0000-0001', '東京都千代田区'),1321 ('佐藤花子', 'hanako@sato.example', '06-0000-0002', '大阪府大阪市');22
23INSERT INTO note (body, created_at, customer_id) VALUES24 ('初回の打ち合わせ。新製品のカタログを渡した。', '2025-04-01T10:00:00.000Z', 1),25 ('見積もりの依頼があった。来週までに送る。', '2025-04-08T15:30:00.000Z', 1);customer_id INTEGER NOT NULL REFERENCES customer(id)は 外部キー です。customerテーブルに無い ID を入れようとすると、データベースがエラーにしますON DELETE CASCADEは、顧客を削除したときに、その顧客のノートも一緒に削除するという指定です。持ち主のいないノートが残らないようにしますDROP TABLEは、外部キーで参照している側(note)から先に消します- 日時は
2025-04-01T10:00:00.000Zのような ISO 8601 の文字列で持ちます。JavaScript のnew Date()でそのまま読めます
データベースを作り直します。それまでに入れたデータは消えて、init.sql の状態に戻ります。
> npm run db:initWeb API を作る
Section titled “Web API を作る”api/src/models/Note.js を作成する
Section titled “api/src/models/Note.js を作成する”1import { DataTypes } from 'sequelize'2import { sequelize } from '../db.js'3
4const Note = sequelize.define('Note', {5 id: {6 type: DataTypes.INTEGER,7 autoIncrement: true,8 primaryKey: true,9 },10 body: {11 type: DataTypes.STRING,12 allowNull: false,13 },14 // 日時は ISO 8601 の文字列(2025-04-01T10:00:00.000Z)で持つ15 createdAt: {16 type: DataTypes.STRING,17 allowNull: false,18 field: 'created_at',19 },20 customerId: {21 type: DataTypes.INTEGER,22 allowNull: false,23 field: 'customer_id',24 },25}, {26 tableName: 'note',27 timestamps: false,28})29
30export default Note- データベースの列は
customer_id・created_atのように_でつなぎ、JavaScript ではcustomerId・createdAtのようにつなげて書くのが一般的です。fieldで、どの列に対応するかを指定します。JSON にもcustomerIdの名前で出ます
モデルどうしの関係(アソシエーション)は、models/index.js にまとめて書きます。
api/src/models/index.js を作成する
Section titled “api/src/models/index.js を作成する”1import Customer from './Customer.js'2import Note from './Note.js'3
4// 1 人の顧客は、たくさんのノートを持つ5Customer.hasMany(Note, { foreignKey: 'customerId', as: 'notes' })6Note.belongsTo(Customer, { foreignKey: 'customerId', as: 'customer' })7
8export { Customer, Note }hasManyは「1 人の顧客がたくさんのノートを持つ」、belongsToは「ノートは 1 人の顧客に属する」を表します(ORMの利用 の会社と部署と同じ形です)- これからは、モデルを使うファイルは
models/index.jsから読み込みます。関係を書いたファイルが必ず読み込まれるようにするためです
顧客のルートに、ノートの一覧と作成を足します。
api/src/routes/customers.js を変更する
Section titled “api/src/routes/customers.js を変更する”11import express from 'express'2import Customer from '../models/Customer.js'2import { Customer, Note } from '../models/index.js'33
44const router = express.Router()6868 res.status(204).end()6969})7070
71router.get('/:id/notes', async (req, res) => {72 const customer = await Customer.findByPk(req.params.id)73
74 if (!customer) {75 return res.status(404).json({ message: '顧客が見つかりません' })76 }77
78 const notes = await Note.findAll({79 where: { customerId: customer.id },80 order: [['createdAt', 'DESC']],81 })82 res.json(notes)83})84
85router.post('/:id/notes', async (req, res) => {86 const customer = await Customer.findByPk(req.params.id)87
88 if (!customer) {89 return res.status(404).json({ message: '顧客が見つかりません' })90 }91
92 const body = req.body ?? {}93 const text = String(body.body ?? '').trim()94
95 if (text === '') {96 return res.status(400).json({ message: 'ノートの本文を入力してください' })97 }98
99 const note = await Note.create({100 body: text,101 createdAt: new Date().toISOString(),102 customerId: customer.id,103 })104 res.status(201).json(note)105})106
71107export default router- どちらも、まず顧客が存在するかを確かめ、無ければ
404を返します - 一覧は
where: { customerId: customer.id }でその顧客のノートだけを取り出し、新しい順(createdAtの降順)に並べます - 書いた日時は Web API で決めます。クライアントから送られてきた値は使いません
ノートの削除は routes/notes.js に書きます。ノートは顧客の下ではなく /notes/:id で指すので、別のルーターにします。
api/src/routes/notes.js を作成する
Section titled “api/src/routes/notes.js を作成する”1import express from 'express'2import { Note } from '../models/index.js'3
4const router = express.Router()5
6router.delete('/:id', async (req, res) => {7 const note = await Note.findByPk(req.params.id)8
9 if (!note) {10 return res.status(404).json({ message: 'ノートが見つかりません' })11 }12
13 await note.destroy()14 res.status(204).end()15})16
17export default routerindex.js で、ノートのルーターを /notes につなげます。
api/src/index.js を変更する
Section titled “api/src/index.js を変更する”11import cors from 'cors'22import express from 'express'33import customers from './routes/customers.js'4import notes from './routes/notes.js'45
56const app = express()1516})1617
1718app.use('/customers', customers)19app.use('/notes', notes)1820
1921// どのルートにも当てはまらなかったリクエスト2022app.use((req, res) => {ブラウザで http://localhost:3000/customers/1/notes を開き、2 件のノートが新しい順に表示されることを確かめます。http://localhost:3000/customers/99/notes は 404 になります。
クライアントを作る
Section titled “クライアントを作る”Web API を呼び出す関数
Section titled “Web API を呼び出す関数”client/src/api.js を変更する
Section titled “client/src/api.js を変更する”4444export async function deleteCustomer(id) {4545 return request(`/customers/${id}`, { method: 'DELETE' })4646}47
48export async function getNotes(customerId) {49 return request(`/customers/${customerId}/notes`)50}51
52export async function createNote(customerId, note) {53 return sendJson('POST', `/customers/${customerId}/notes`, note)54}55
56export async function deleteNote(id) {57 return request(`/notes/${id}`, { method: 'DELETE' })58}ノートの部品
Section titled “ノートの部品”ノートの一覧と追加のフォームは、顧客詳細の画面の中に置く 部品(コンポーネント)として作ります。画面(routes/)ではない部品は src/components/ に置きます。
client/src/components/CustomerNotes.jsx を作成する
Section titled “client/src/components/CustomerNotes.jsx を作成する”1import { useEffect, useState } from 'react'2import { createNote, deleteNote, getNotes } from '../api'3
4function CustomerNotes({ customerId }) {5 const [notes, setNotes] = useState([])6 const [body, setBody] = useState('')7 const [loading, setLoading] = useState(false)8 const [error, setError] = useState(null)9
10 async function load(customerId) {11 setLoading(true)12 setError(null)13 try {14 const notes = await getNotes(customerId)15 setNotes(notes)16 } catch (error) {17 setError(error)18 } finally {19 setLoading(false)20 }21 }22
23 useEffect(() => {24 load(customerId)25 }, [customerId])26
27 async function handleSubmit(event) {28 event.preventDefault()29 setLoading(true)30 setError(null)31 try {32 await createNote(customerId, { body })33 setBody('')34 // 作成したノートを含めて、Web API から一覧を読み込み直す35 await load(customerId)36 } catch (error) {37 setError(error)38 setLoading(false)39 }40 }41
42 async function handleDelete(id) {43 if (!confirm('ノートを削除しますか?')) return44 setLoading(true)45 setError(null)46 try {47 await deleteNote(id)48 await load(customerId)49 } catch (error) {50 setError(error)51 setLoading(false)52 }53 }54
55 return (56 <section>57 <h2>ノート</h2>58 <form onSubmit={handleSubmit}>59 <div>60 <textarea61 name="body" value={body}62 onChange={(event) => setBody(event.target.value)} />63 </div>64 <button type="submit" disabled={loading}>ノートを追加</button>65 </form>66 {loading && <p>読み込み中...</p>}67 {error && <p>エラーが発生しました: {error.message}</p>}68 {!loading && !error && notes.length < 1 && <p>ノートはまだありません</p>}69 <ul>70 {notes.map((note) => (71 <li key={note.id}>72 <p>{note.body}</p>73 <p>74 <small>{new Date(note.createdAt).toLocaleString()}</small>75 {' '}76 <button type="button" onClick={() => handleDelete(note.id)} disabled={loading}>削除</button>77 </p>78 </li>79 ))}80 </ul>81 </section>82 )83}84
85export default CustomerNotescustomerIdを props で受け取り(コンポーネント)、その顧客のノートを読み込みます- 追加・削除に成功したら、
load()で Web API から一覧を読み込み直します。画面の state を自分で書き換えるより、データベースの本物を取り直すほうが、表示と保存された内容がずれません new Date(note.createdAt).toLocaleString()で、日時をブラウザの地域の形式(日本なら2025/4/1 19:00:00)で表示します
顧客詳細に置く
Section titled “顧客詳細に置く”client/src/routes/CustomerSingle.jsx を変更する
Section titled “client/src/routes/CustomerSingle.jsx を変更する”11import { useEffect, useState } from 'react'22import { Link, useNavigate, useParams } from 'react-router-dom'33import { deleteCustomer, getCustomer, updateCustomer } from '../api'4import CustomerNotes from '../components/CustomerNotes'45
56function CustomerSingle() {67 const params = useParams()9899 <button type="button" onClick={handleDelete} disabled={loading}>削除</button>99100 </form>100101 )}102 {customer && <CustomerNotes customerId={customer.id} />}101103 <hr />102104 <Link to="/">顧客一覧に戻る</Link>103105</div>顧客を読み込めたあと(customer が入ってから)に、ノートの部品を表示します。
api と client の両方を起動して、次のことを確かめます。
- 山田太郎の詳細に、2 件のノートが新しい順に表示される
- ノートを追加すると、一覧のいちばん上に表示される
- 本文を空にして追加すると、エラーのメッセージが表示される
- ノートを削除すると、一覧から消える
- ノートのある顧客を削除してから SQLiteBrowser などで
noteテーブルを見ると、その顧客のノートも消えている(ON DELETE CASCADE)
- ノートを編集できるようにしてみましょう。Web API に
PUT /notes/:idを足し、CustomerNotesの各ノートに編集のフォームを出します - 04 章の 機能追加(ノート) のように、ノートの一覧・詳細・作成を別の画面に分ける作り方も考えてみましょう。この節のように 1 つの画面にまとめる場合と比べて、どちらが使いやすいでしょうか
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”よくある質問
Section titled “よくある質問”SQLITE_ERROR: no such table: note と出ます
init.sql を変えたあとに、データベースを作り直していません。api のフォルダで npm run db:init を実行してください。
データを消さずにテーブルを足すことはできないのですか?
CREATE TABLE note (...) だけを実行すれば、ほかのテーブルのデータは残ります。実際のアプリでは、データベースの変更を「マイグレーション」というファイルに 1 つずつ書いて、順番に当てていくのが一般的です。この教材では手順を簡単にするために、毎回 init.sql で作り直しています。
顧客を削除したらノートも消えるのは困りませんか?
困る場合もあります。そのときは ON DELETE CASCADE の代わりに、ノートがある顧客は削除できないようにする(Web API で 409 などのエラーを返す)、削除する代わりに「削除済み」の印を付ける、といった方法があります。どうするのがよいかは、アプリの使われ方で決めます。