一覧を実装する
GET /notes(一覧)を実装し、一覧を見る画面を作ります。
コントローラーに書く
Section titled “コントローラーに書く”apps/api/src/notes/notes.controller.ts を変更する
Section titled “apps/api/src/notes/notes.controller.ts を変更する”1import { Body, Controller, Post } from '@nestjs/common';1import { Body, Controller, Get, Post } from '@nestjs/common';22import { randomUUID } from 'node:crypto';33import { openDatabase } from '../database.js';3434 .run(note);3535 return note;3636 }37
38 @Get()39 findAll(): Note[] {40 return this.db41 .prepare('SELECT * FROM notes ORDER BY createdAt')42 .all() as Note[];43 }3744}@Get()…GET /notesを受け付けますprepare(...).all()… すべての行を配列で返します。作った順(createdAt)に並べます
一覧の画面を作る
Section titled “一覧の画面を作る”apps/ui/notes.html を作成する
Section titled “apps/ui/notes.html を作成する”1<!doctype html>2<html lang="ja">3<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 <title>ノートの一覧</title>7 <link rel="stylesheet" href="./style.css">8</head>9<body>10 <h1>ノートの一覧</h1>11 <ul id="notes"></ul>12
13 <script type="module" src="./notes.js"></script>14</body>15</html>apps/ui/notes.js を作成する
Section titled “apps/ui/notes.js を作成する”1import { apiUrl } from './lib/api.js';2
3// GET /notes を呼んで、ノートを並べる(トークンは要らない)4const notes = await (await fetch(`${apiUrl}/notes`)).json();5const list = document.querySelector('#notes');6for (const note of notes) {7 const item = document.createElement('li');8 // textContent で入れる(innerHTML だと、ノートに書いた HTML が動いてしまう)9 item.textContent = `${note.title}: ${note.body}`;10 list.append(item);11}12if (notes.length === 0) list.textContent = 'ノートはまだありません';item.textContent = ...…innerHTMLだと、ノートに書いた HTML が画面で動いてしまうので、文字として入れます
動作確認する
Section titled “動作確認する”podman compose up -d --build --waitcurl -i http://localhost:3001/notes1 行目が HTTP/1.1 200 OK で、最後の行に、これまでに作ったノートの配列が出れば大丈夫です。
ブラウザで http://localhost:3000/notes.html を開くと、ノートの題名と本文が並びます。
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- NestJS: Controllers …
@Get() - Node.js: SQLite …
statement.all() - MDN: Node.textContent …
innerHTMLとの違い