顧客の管理
顧客管理アプリ(フロントエンド版) では、データをブラウザの localStorage に保存していました。そのため、データはそのブラウザの中にしかなく、ほかの人と共有できませんでした。
この章では、同じ顧客管理アプリを、クライアントと Web API の連携 と同じ形(React のクライアント + Express の Web API + SQLite のデータベース)で作り直します。データがサーバーのデータベースに入るので、同じ Web API を使う人どうしでデータを共有できます。
---
title: 04 章の形
---
graph LR
subgraph ブラウザ
Client[クライアント] -->|非同期処理| localStorage
end
---
title: この章の形
---
graph LR
subgraph ブラウザ
Client[クライアント]
end
subgraph サーバー
WebAPI[Web API] --> Database[(データベース)]
end
Client -->|"fetch(HTTP + JSON)"| WebAPI
04 章で storage.js の関数を非同期にしておいたのは、この置き換えのためでした。画面のコンポーネントから見ると、呼び出す関数が storage.js から api.js に変わるだけです。
この章の節では、要望に応えて機能を足していきます。
| 節 | 要望 | 足すもの |
|---|---|---|
| 顧客の管理(この節) | 顧客の連絡先を一覧したい | 顧客の CRUD |
| 機能追加(ノート) | 顧客ごとにメモを残したい | ノート |
| 機能追加(組織) | 顧客を会社などの組織で分けたい | 組織 |
| 機能追加(権限) | 大事なデータは管理者だけが消せるようにしたい | 利用者と役割 |
データを考える
Section titled “データを考える”04 章と同じく、顧客の名前・メールアドレス・電話番号・住所を管理します。
erDiagram
customer["顧客"] {
int id "顧客ID"
string name "名前"
string email "メールアドレス"
string tel "電話番号"
string address "住所"
}
04 章では ID を customer-1700000000000 のような文字列で自分で作っていましたが、この章ではデータベースが 1, 2, 3, ... と番号を振ります(INTEGER PRIMARY KEY AUTOINCREMENT)。
画面を考える
Section titled “画面を考える”graph LR A[顧客一覧] --> B[顧客詳細] A --> C[顧客作成]
| 画面名 | パス | コンポーネント | 説明 |
|---|---|---|---|
| 顧客一覧 | / |
CustomerCollection |
顧客の一覧を表示する |
| 顧客作成 | /customers/new |
CustomerCreate |
顧客を作成する |
| 顧客詳細 | /customers/:customerId |
CustomerSingle |
顧客の詳細を表示し、編集と削除を行う |
Web API を考える
Section titled “Web API を考える”画面の機能ごとに、使う Web API を決めます。
| 機能 | 画面 | クライアントの関数 | Web API |
|---|---|---|---|
| 顧客一覧表示 | 顧客一覧 | getCustomers() |
GET /customers |
| 顧客詳細表示 | 顧客詳細 | getCustomer(id) |
GET /customers/:id |
| 顧客作成 | 顧客作成 | createCustomer(customer) |
POST /customers |
| 顧客編集 | 顧客詳細 | updateCustomer(customer) |
PUT /customers/:id |
| 顧客削除 | 顧客詳細 | deleteCustomer(id) |
DELETE /customers/:id |
プロジェクトを作る
Section titled “プロジェクトを作る”my-crm フォルダの中に、api と client の 2 つのプロジェクトを作ります。手順は クライアントからのWebAPIの呼び出し と データの取得と表示 と同じです。
my-crm├── api … Web API(http://localhost:3000)└── client … クライアント(http://localhost:5173)Web API
Section titled “Web API”> mkdir my-crm> cd my-crm> mkdir api> cd api> npm init -y> npm pkg set type=module> npm pkg set "scripts.dev=node --watch src/index.js"> npm pkg set "scripts.start=node src/index.js"> npm pkg set "scripts.db:init=node db/init.js"> npm pkg delete scripts.test> npm install express cors sequelize sqlite3api/package.json が作られる
Section titled “api/package.json が作られる”1{2 "name": "api",3 "version": "1.0.0",4 "description": "",5 "main": "index.js",6 "scripts": {7 "dev": "node --watch src/index.js",8 "start": "node src/index.js",9 "db:init": "node db/init.js"10 },11 "keywords": [],12 "author": "",13 "license": "ISC",14 "type": "module",15 "dependencies": {16 "cors": "^2.8.6",17 "express": "^5.3.0",18 "sequelize": "^6.37.8",19 "sqlite3": "^6.0.1"20 }21}クライアント
Section titled “クライアント”別のターミナルで、my-crm のフォルダに戻ってから作ります。
> npm create vite@latest client -- --template react> cd client> npm install> npm install react-router-domclient/package.json が作られる
Section titled “client/package.json が作られる”1{2 "name": "client",3 "private": true,4 "version": "0.0.0",5 "type": "module",6 "scripts": {7 "dev": "vite",8 "build": "vite build",9 "lint": "oxlint",10 "preview": "vite preview"11 },12 "dependencies": {13 "react": "^19.3.1",14 "react-dom": "^19.3.1",15 "react-router-dom": "^7.18.7"16 },17 "devDependencies": {18 "@types/react": "^19.3.0",19 "@types/react-dom": "^19.3.0",20 "@vitejs/plugin-react": "^6.3.0",21 "oxlint": "^1.94.0",22 "vite": "^8.4.0"23 }24}src/App.css・src/index.css・src/assets/ を消し、src/main.jsx から index.css を読み込む行を消します。
client/src/main.jsx を変更する
Section titled “client/src/main.jsx を変更する”11import { StrictMode } from 'react'22import { createRoot } from 'react-dom/client'3import './index.css'43import App from './App.jsx'54
65createRoot(document.getElementById('root')).render(データベースを用意する
Section titled “データベースを用意する”customer テーブルを作り、確認用のデータを 2 件入れます。
api/db/init.sql を作成する
Section titled “api/db/init.sql を作成する”1DROP TABLE IF EXISTS customer;2
3CREATE TABLE customer (4 id INTEGER PRIMARY KEY AUTOINCREMENT,5 name TEXT NOT NULL,6 email TEXT NOT NULL DEFAULT '',7 tel TEXT NOT NULL DEFAULT '',8 address TEXT NOT NULL DEFAULT ''9);10
11INSERT INTO customer (name, email, tel, address) VALUES12 ('山田太郎', 'taro@yamada.example', '03-0000-0001', '東京都千代田区'),13 ('佐藤花子', 'hanako@sato.example', '06-0000-0002', '大阪府大阪市');init.sql をデータベースに流すスクリプトは、03 章と同じものです。
api/db/init.js を作成する
Section titled “api/db/init.js を作成する”1import { readFileSync } from 'node:fs'2import sqlite3 from 'sqlite3'3
4// init.sql を読み込んで、database.sqlite に流す(テーブルを作り直して、最初のデータを入れる)5const sql = readFileSync(new URL('./init.sql', import.meta.url), 'utf8')6const db = new sqlite3.Database('./database.sqlite')7
8db.exec(sql, (error) => {9 if (error) {10 console.error(error)11 process.exitCode = 112 } else {13 console.log('database.sqlite を初期化しました')14 }15 db.close()16})> npm run db:initdatabase.sqlite を初期化しましたWeb API を作る
Section titled “Web API を作る”データベースへの接続とモデル
Section titled “データベースへの接続とモデル”api/src/db.js を作成する
Section titled “api/src/db.js を作成する”1import { Sequelize } from 'sequelize'2
3export const sequelize = new Sequelize({4 dialect: 'sqlite',5 storage: './database.sqlite',6 logging: false,7})api/src/models/Customer.js を作成する
Section titled “api/src/models/Customer.js を作成する”1import { DataTypes } from 'sequelize'2import { sequelize } from '../db.js'3
4const Customer = sequelize.define('Customer', {5 id: {6 type: DataTypes.INTEGER,7 autoIncrement: true,8 primaryKey: true,9 },10 name: {11 type: DataTypes.STRING,12 allowNull: false,13 },14 email: {15 type: DataTypes.STRING,16 allowNull: false,17 defaultValue: '',18 },19 tel: {20 type: DataTypes.STRING,21 allowNull: false,22 defaultValue: '',23 },24 address: {25 type: DataTypes.STRING,26 allowNull: false,27 defaultValue: '',28 },29}, {30 tableName: 'customer',31 timestamps: false,32})33
34export default Customerルートをファイルに分ける
Section titled “ルートをファイルに分ける”この章では、組織やノートの Web API も足していきます。すべてを index.js に書くと長くなるので、顧客に関するルートは src/routes/customers.js に分けます。
03 章のタスクと同じく、express.Router() で作ったルーターに顧客のルートを書き、app.use('/customers', customers) でアプリにつなげます(Express のドキュメント)。customers.js の中では、/customers を省いたパスで書きます。
flowchart LR
Index["index.js<br>app"] -->|"app.use('/customers', ...)"| Customers["routes/customers.js<br>router"]
Customers --> R1["get('/') → GET /customers"]
Customers --> R2["get('/:id') → GET /customers/:id"]
Customers --> R3["post('/') → POST /customers"]
Customers --> R4["put('/:id') → PUT /customers/:id"]
Customers --> R5["delete('/:id') → DELETE /customers/:id"]
api/src/routes/customers.js を作成する
Section titled “api/src/routes/customers.js を作成する”1import express from 'express'2import Customer from '../models/Customer.js'3
4const router = express.Router()5
6// リクエストの本文から、保存してよい値だけを取り出す。7// 本文が JSON でないときは req.body が undefined なので、body = {} として扱う8function readCustomer(body = {}) {9 return {10 name: String(body.name ?? '').trim(),11 email: String(body.email ?? ''),12 tel: String(body.tel ?? ''),13 address: String(body.address ?? ''),14 }15}16
17router.get('/', async (req, res) => {18 const list = await Customer.findAll({ order: [['id', 'ASC']] })19 res.json(list)20})21
22router.get('/:id', async (req, res) => {23 const customer = await Customer.findByPk(req.params.id)24
25 if (!customer) {26 return res.status(404).json({ message: '顧客が見つかりません' })27 }28
29 res.json(customer)30})31
32router.post('/', async (req, res) => {33 const values = readCustomer(req.body)34
35 if (values.name === '') {36 return res.status(400).json({ message: '名前を入力してください' })37 }38
39 const customer = await Customer.create(values)40 res.status(201).json(customer)41})42
43router.put('/:id', async (req, res) => {44 const customer = await Customer.findByPk(req.params.id)45
46 if (!customer) {47 return res.status(404).json({ message: '顧客が見つかりません' })48 }49
50 const values = readCustomer(req.body)51
52 if (values.name === '') {53 return res.status(400).json({ message: '名前を入力してください' })54 }55
56 await customer.update(values)57 res.json(customer)58})59
60router.delete('/:id', async (req, res) => {61 const customer = await Customer.findByPk(req.params.id)62
63 if (!customer) {64 return res.status(404).json({ message: '顧客が見つかりません' })65 }66
67 await customer.destroy()68 res.status(204).end()69})70
71export default routerreadCustomer()は、リクエストの本文から保存してよい値だけを取り出します。idなど、利用者に決めさせたくない値が送られてきても、データベースには入りません- 本文が JSON でないときは
req.bodyがundefinedになるので、readCustomer(body = {})で空のオブジェクトとして扱います - 名前が空なら
400を返します - それ以外は データの作成と更新と削除 のタスクと同じ形です
api/src/index.js を作成する
Section titled “api/src/index.js を作成する”1import cors from 'cors'2import express from 'express'3import customers from './routes/customers.js'4
5const app = express()6
7app.use(cors({8 origin: 'http://localhost:5173',9}))10// リクエストの本文の JSON を読み、req.body に入れる11app.use(express.json())12
13app.get('/', (req, res) => {14 res.send('my-crm API')15})16
17app.use('/customers', customers)18
19// どのルートにも当てはまらなかったリクエスト20app.use((req, res) => {21 res.status(404).json({ message: '見つかりません' })22})23
24// ルートやミドルウェアの中で起きたエラー(データベースのエラーなど)は、ここに届く25app.use((err, req, res, next) => {26 // express.json() が本文を読めなかったとき(JSON の書き方の誤りなど)は、err.status に 400 番台が入っている27 if (err.status >= 400 && err.status < 500) {28 return res.status(err.status).json({ message: 'リクエストの本文を読めませんでした' })29 }30
31 console.error(err)32 res.status(500).json({ message: 'サーバーでエラーが発生しました' })33})34
35app.listen(3000, (error) => {36 if (error) {37 throw error38 }39 console.log('Server is running on http://localhost:3000')40})- CORS(
http://localhost:5173だけを許可)、本文の JSON を読むexpress.json()、見つからないときの404、エラーのミドルウェアは、データの作成と更新と削除 のindex.jsと同じです - ルートは
routes/のルーターに分けたので、index.jsにはアプリ全体の設定と、ルーターをつなげるapp.use()だけが残ります
> npm run devhttp://localhost:3000/customers を開き、2 件の顧客が JSON で表示されることを確かめます。
クライアントを作る
Section titled “クライアントを作る”Web API を呼び出す関数
Section titled “Web API を呼び出す関数”04 章の storage.js に当たるファイルです。関数の名前と引数を 04 章とそろえているので、画面からの使い方はほとんど同じです。
client/src/api.js を作成する
Section titled “client/src/api.js を作成する”1const API_URL = 'http://localhost:3000'2
3async function request(path, options = {}) {4 const response = await fetch(`${API_URL}${path}`, options)5
6 // 404 や 500 でも fetch はエラーにならないので、ok(200 番台か)を自分で確かめる7 if (!response.ok) {8 const body = await response.json().catch(() => null)9 throw new Error(body?.message ?? `${response.status} ${response.statusText}`)10 }11
12 // 204 No Content は本文が無いので、JSON として読まない13 if (response.status === 204) {14 return null15 }16
17 return response.json()18}19
20function sendJson(method, path, data) {21 return request(path, {22 method,23 headers: { 'Content-Type': 'application/json' },24 body: JSON.stringify(data),25 })26}27
28export async function getCustomers() {29 return request('/customers')30}31
32export async function getCustomer(id) {33 return request(`/customers/${id}`)34}35
36export async function createCustomer(customer) {37 return sendJson('POST', '/customers', customer)38}39
40export async function updateCustomer(customer) {41 return sendJson('PUT', `/customers/${customer.id}`, customer)42}43
44export async function deleteCustomer(id) {45 return request(`/customers/${id}`, { method: 'DELETE' })46}sendJson()は、JSON を送るPOSTとPUTで共通の処理です。03 章では関数ごとに書いていたheadersとbodyをまとめました
client/src/App.jsx を作成する
Section titled “client/src/App.jsx を作成する”1import { BrowserRouter, Route, Routes } from 'react-router-dom'2import CustomerCollection from './routes/CustomerCollection'3import CustomerCreate from './routes/CustomerCreate'4import CustomerSingle from './routes/CustomerSingle'5
6function App() {7 return (8 <BrowserRouter>9 <Routes>10 <Route path="/" element={<CustomerCollection />} />11 <Route path="/customers/new" element={<CustomerCreate />} />12 <Route path="/customers/:customerId" element={<CustomerSingle />} />13 </Routes>14 </BrowserRouter>15 )16}17
18export default Appclient/src/routes/CustomerCollection.jsx を作成する
Section titled “client/src/routes/CustomerCollection.jsx を作成する”1import { useEffect, useState } from 'react'2import { Link } from 'react-router-dom'3import { getCustomers } from '../api'4
5function CustomerCollection() {6 const [customers, setCustomers] = useState([])7 const [loading, setLoading] = useState(false)8 const [error, setError] = useState(null)9
10 async function load() {11 setLoading(true)12 setError(null)13 try {14 const customers = await getCustomers()15 setCustomers(customers)16 } catch (error) {17 setError(error)18 } finally {19 setLoading(false)20 }21 }22
23 useEffect(() => {24 load()25 }, [])26
27 return (28 <div>29 <h1>顧客一覧</h1>30 <p>31 <Link to="/customers/new">新規作成</Link>32 </p>33 {loading && <p>読み込み中...</p>}34 {error && <p>エラーが発生しました: {error.message}</p>}35 {!loading && !error && customers.length < 1 && <p>顧客が登録されていません</p>}36 <ul>37 {customers.map((customer) => (38 <li key={customer.id}>39 <Link to={`/customers/${customer.id}`}>{customer.name}</Link>40 </li>41 ))}42 </ul>43 </div>44 )45}46
47export default CustomerCollectionclient/src/routes/CustomerCreate.jsx を作成する
Section titled “client/src/routes/CustomerCreate.jsx を作成する”1import { useState } from 'react'2import { Link, useNavigate } from 'react-router-dom'3import { createCustomer } from '../api'4
5function CustomerCreate() {6 const navigate = useNavigate()7 const [values, setValues] = useState({8 name: '',9 email: '',10 tel: '',11 address: '',12 })13 const [saving, setSaving] = useState(false)14 const [error, setError] = useState(null)15
16 async function handleSubmit(event) {17 event.preventDefault()18 setSaving(true)19 setError(null)20 try {21 const customer = await createCustomer(values)22 navigate(`/customers/${customer.id}`)23 } catch (error) {24 setError(error)25 } finally {26 setSaving(false)27 }28 }29
30 return (31 <div>32 <h1>顧客作成</h1>33 {error && <p>エラーが発生しました: {error.message}</p>}34 <form onSubmit={handleSubmit}>35 <div>36 <label>37 名前:38 <input39 type="text" name="name" value={values.name}40 onChange={(event) => setValues({ ...values, name: event.target.value })} />41 </label>42 </div>43 <div>44 <label>45 メールアドレス:46 <input47 type="email" name="email" value={values.email}48 onChange={(event) => setValues({ ...values, email: event.target.value })} />49 </label>50 </div>51 <div>52 <label>53 電話番号:54 <input55 type="tel" name="tel" value={values.tel}56 onChange={(event) => setValues({ ...values, tel: event.target.value })} />57 </label>58 </div>59 <div>60 <label>61 住所:62 <textarea63 name="address" value={values.address}64 onChange={(event) => setValues({ ...values, address: event.target.value })} />65 </label>66 </div>67 <button type="submit" disabled={saving}>作成</button>68 </form>69 <hr />70 <Link to="/">顧客一覧に戻る</Link>71 </div>72 )73}74
75export default CustomerCreate- 作成に成功すると、Web API が返した顧客の
idで詳細の画面に移ります
client/src/routes/CustomerSingle.jsx を作成する
Section titled “client/src/routes/CustomerSingle.jsx を作成する”1import { useEffect, useState } from 'react'2import { Link, useNavigate, useParams } from 'react-router-dom'3import { deleteCustomer, getCustomer, updateCustomer } from '../api'4
5function CustomerSingle() {6 const params = useParams()7 const navigate = useNavigate()8 const [customer, setCustomer] = useState(null)9 const [loading, setLoading] = useState(false)10 const [error, setError] = useState(null)11
12 async function load(id) {13 setLoading(true)14 setError(null)15 try {16 const customer = await getCustomer(id)17 setCustomer(customer)18 } catch (error) {19 setError(error)20 } finally {21 setLoading(false)22 }23 }24
25 useEffect(() => {26 load(params.customerId)27 }, [params.customerId])28
29 async function handleSubmit(event) {30 event.preventDefault()31 setLoading(true)32 setError(null)33 try {34 const updated = await updateCustomer(customer)35 setCustomer(updated)36 alert('保存しました')37 } catch (error) {38 setError(error)39 } finally {40 setLoading(false)41 }42 }43
44 async function handleDelete() {45 if (!confirm('削除しますか?')) return46 setLoading(true)47 setError(null)48 try {49 await deleteCustomer(customer.id)50 navigate('/')51 } catch (error) {52 setError(error)53 setLoading(false)54 }55 }56
57 return (58 <div>59 <h1>顧客詳細</h1>60 {loading && <p>読み込み中...</p>}61 {error && <p>エラーが発生しました: {error.message}</p>}62 {customer && (63 <form onSubmit={handleSubmit}>64 <p>ID: {customer.id}</p>65 <div>66 <label>67 名前:68 <input69 type="text" name="name" value={customer.name}70 onChange={(event) => setCustomer({ ...customer, name: event.target.value })} />71 </label>72 </div>73 <div>74 <label>75 メールアドレス:76 <input77 type="email" name="email" value={customer.email}78 onChange={(event) => setCustomer({ ...customer, email: event.target.value })} />79 </label>80 </div>81 <div>82 <label>83 電話番号:84 <input85 type="tel" name="tel" value={customer.tel}86 onChange={(event) => setCustomer({ ...customer, tel: event.target.value })} />87 </label>88 </div>89 <div>90 <label>91 住所:92 <textarea93 name="address" value={customer.address}94 onChange={(event) => setCustomer({ ...customer, address: event.target.value })} />95 </label>96 </div>97 <button type="submit" disabled={loading}>保存</button>98 <button type="button" onClick={handleDelete} disabled={loading}>削除</button>99 </form>100 )}101 <hr />102 <Link to="/">顧客一覧に戻る</Link>103 </div>104 )105}106
107export default CustomerSingle04 章の画面との違いは次のとおりです。
| 04 章(localStorage) | この節(Web API) | |
|---|---|---|
| データを読み書きする関数 | storage.js |
api.js |
| ID | クライアントが作る文字列 | データベースが振る番号 |
| 入力の確認 | 無し | Web API が確かめて 400 を返す |
| 見つからないとき | 関数がエラーを投げる | Web API が 404 を返し、api.js がエラーを投げる |
| データの置き場所 | そのブラウザの中だけ | サーバーのデータベース |
api と client の両方で npm run dev を実行し、http://localhost:5173/ を開いて確かめます。
- 顧客一覧に 2 件の顧客が表示される
- 顧客を作成すると、作成した顧客の詳細が表示される
- 名前を空にして作成・保存すると、エラーのメッセージが表示される
- 顧客を編集して保存し、一覧に戻ると変わっている
- 顧客を削除すると一覧に戻り、一覧から消えている
ほかのブラウザから見る
Section titled “ほかのブラウザから見る”04 章では、別のブラウザ(Chrome と Edge など)で開くとデータは共有されませんでした。いまは、別のブラウザで http://localhost:5173/ を開いても同じ顧客が表示されます。データがブラウザではなく、Web API の先のデータベースにあるからです。
- 04 章の
storage.jsを、Web API を呼び出すapi.jsに置き換えた - 顧客のルートを
routes/customers.jsのルーターに分け、app.use()でつないだ - 入力の確認と ID の採番は、Web API とデータベースが受け持つ
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”よくある質問
Section titled “よくある質問”一覧が「エラーが発生しました: Failed to fetch」になります
Web API が起動していないか、CORS で止められています。api のターミナルで npm run dev が動いているか、index.js の cors() の origin が http://localhost:5173 になっているかを確かめてください。
04 章で作った localStorage のデータを移せますか?
この章では移しません。どうしても移したいときは、04 章のアプリを開いた状態で開発者ツールのコンソールから JSON.parse(localStorage.getItem('customers')) で取り出し、fetch で POST /customers に 1 件ずつ送る方法があります。
api と client を 1 つのコマンドで起動できませんか?
concurrently などのパッケージを使うと、1 つのターミナルで両方を起動できます。この教材では、どちらのサーバーのログなのかが分かりやすいように、ターミナルを分けています。