コンテンツにスキップ

機能追加(ノート)

機能追加(ノート)

顧客管理アプリを友人に見せたところ、次のような要望をもらいました。

顧客ごとに、打ち合わせの内容などのメモを残したい

この要望に応えるために、顧客ごとにノートを書けるようにします。

前の節を終えていない人は、ここから始められます。api で npm install と npm run db:init、client で npm install を実行してから始めてください。

この節を始めるときのファイル

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対多"

ノートは顧客の詳細の画面の中に表示し、その場で追加・削除できるようにします。

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 にします。

note テーブルを足します。

api/db/init.sql
1
DROP TABLE IF EXISTS note;
1
2
DROP TABLE IF EXISTS customer;
2
3
3
4
CREATE TABLE customer (
api/db/init.sql
8
9
address TEXT NOT NULL DEFAULT ''
9
10
);
10
11
12
CREATE 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 CASCADE
17
);
18
11
19
INSERT INTO customer (name, email, tel, address) VALUES
12
20
('山田太郎', 'taro@yamada.example', '03-0000-0001', '東京都千代田区'),
13
21
('佐藤花子', 'hanako@sato.example', '06-0000-0002', '大阪府大阪市');
22
23
INSERT INTO note (body, created_at, customer_id) VALUES
24
('初回の打ち合わせ。新製品のカタログを渡した。', '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:init
api/src/models/Note.js
1
import { DataTypes } from 'sequelize'
2
import { sequelize } from '../db.js'
3
4
const 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
30
export default Note
  • データベースの列は customer_id・created_at のように _ でつなぎ、JavaScript では customerId・createdAt のようにつなげて書くのが一般的です。field で、どの列に対応するかを指定します。JSON にも customerId の名前で出ます

モデルどうしの関係(アソシエーション)は、models/index.js にまとめて書きます。

api/src/models/index.js
1
import Customer from './Customer.js'
2
import Note from './Note.js'
3
4
// 1 人の顧客は、たくさんのノートを持つ
5
Customer.hasMany(Note, { foreignKey: 'customerId', as: 'notes' })
6
Note.belongsTo(Customer, { foreignKey: 'customerId', as: 'customer' })
7
8
export { Customer, Note }
  • hasMany は「1 人の顧客がたくさんのノートを持つ」、belongsTo は「ノートは 1 人の顧客に属する」を表します(ORMの利用 の会社と部署と同じ形です)
  • これからは、モデルを使うファイルは models/index.js から読み込みます。関係を書いたファイルが必ず読み込まれるようにするためです

顧客のルートに、ノートの一覧と作成を足します。

api/src/routes/customers.js を変更する

Section titled “api/src/routes/customers.js を変更する”
api/src/routes/customers.js
1
1
import express from 'express'
2
import Customer from '../models/Customer.js'
2
import { Customer, Note } from '../models/index.js'
3
3
4
4
const router = express.Router()
api/src/routes/customers.js
68
68
res.status(204).end()
69
69
})
70
70
71
router.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
85
router.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
71
107
export default router
  • どちらも、まず顧客が存在するかを確かめ、無ければ 404 を返します
  • 一覧は where: { customerId: customer.id } でその顧客のノートだけを取り出し、新しい順(createdAt の降順)に並べます
  • 書いた日時は Web API で決めます。クライアントから送られてきた値は使いません

ノートの削除は routes/notes.js に書きます。ノートは顧客の下ではなく /notes/:id で指すので、別のルーターにします。

api/src/routes/notes.js
1
import express from 'express'
2
import { Note } from '../models/index.js'
3
4
const router = express.Router()
5
6
router.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
17
export default router

index.js で、ノートのルーターを /notes につなげます。

api/src/index.js
1
1
import cors from 'cors'
2
2
import express from 'express'
3
3
import customers from './routes/customers.js'
4
import notes from './routes/notes.js'
4
5
5
6
const app = express()
api/src/index.js
15
16
})
16
17
17
18
app.use('/customers', customers)
19
app.use('/notes', notes)
18
20
19
21
// どのルートにも当てはまらなかったリクエスト
20
22
app.use((req, res) => {

ブラウザで http://localhost:3000/customers/1/notes を開き、2 件のノートが新しい順に表示されることを確かめます。http://localhost:3000/customers/99/notes は 404 になります。

client/src/api.js
44
44
export async function deleteCustomer(id) {
45
45
return request(`/customers/${id}`, { method: 'DELETE' })
46
46
}
47
48
export async function getNotes(customerId) {
49
return request(`/customers/${customerId}/notes`)
50
}
51
52
export async function createNote(customerId, note) {
53
return sendJson('POST', `/customers/${customerId}/notes`, note)
54
}
55
56
export async function deleteNote(id) {
57
return request(`/notes/${id}`, { method: 'DELETE' })
58
}

ノートの一覧と追加のフォームは、顧客詳細の画面の中に置く 部品(コンポーネント)として作ります。画面(routes/)ではない部品は src/components/ に置きます。

client/src/components/CustomerNotes.jsx を作成する

Section titled “client/src/components/CustomerNotes.jsx を作成する”
client/src/components/CustomerNotes.jsx
1
import { useEffect, useState } from 'react'
2
import { createNote, deleteNote, getNotes } from '../api'
3
4
function 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('ノートを削除しますか?')) return
44
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
<textarea
61
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
85
export default CustomerNotes
  • customerId を props で受け取り(コンポーネント)、その顧客のノートを読み込みます
  • 追加・削除に成功したら、load() で Web API から一覧を読み込み直します。画面の state を自分で書き換えるより、データベースの本物を取り直すほうが、表示と保存された内容がずれません
  • new Date(note.createdAt).toLocaleString() で、日時をブラウザの地域の形式(日本なら 2025/4/1 19:00:00)で表示します

client/src/routes/CustomerSingle.jsx を変更する

Section titled “client/src/routes/CustomerSingle.jsx を変更する”
client/src/routes/CustomerSingle.jsx
1
1
import { useEffect, useState } from 'react'
2
2
import { Link, useNavigate, useParams } from 'react-router-dom'
3
3
import { deleteCustomer, getCustomer, updateCustomer } from '../api'
4
import CustomerNotes from '../components/CustomerNotes'
4
5
5
6
function CustomerSingle() {
6
7
const params = useParams()
client/src/routes/CustomerSingle.jsx
98
99
<button type="button" onClick={handleDelete} disabled={loading}>削除</button>
99
100
</form>
100
101
)}
102
{customer && <CustomerNotes customerId={customer.id} />}
101
103
<hr />
102
104
<Link to="/">顧客一覧に戻る</Link>
103
105
</div>

顧客を読み込めたあと(customer が入ってから)に、ノートの部品を表示します。

api と client の両方を起動して、次のことを確かめます。

  • 山田太郎の詳細に、2 件のノートが新しい順に表示される
  • ノートを追加すると、一覧のいちばん上に表示される
  • 本文を空にして追加すると、エラーのメッセージが表示される
  • ノートを削除すると、一覧から消える
  • ノートのある顧客を削除してから SQLiteBrowser などで note テーブルを見ると、その顧客のノートも消えている(ON DELETE CASCADE)
  • ノートを編集できるようにしてみましょう。Web API に PUT /notes/:id を足し、CustomerNotes の各ノートに編集のフォームを出します
  • 04 章の 機能追加(ノート) のように、ノートの一覧・詳細・作成を別の画面に分ける作り方も考えてみましょう。この節のように 1 つの画面にまとめる場合と比べて、どちらが使いやすいでしょうか

この節を終えたときのディレクトリ

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 などのエラーを返す)、削除する代わりに「削除済み」の印を付ける、といった方法があります。どうするのがよいかは、アプリの使われ方で決めます。