コンテンツにスキップ

Get を実装する

04 章 Get を実装する

GET /notes/{id}(Get)を実装します。

api/src/notes/notes.controller.ts を変更する

Section titled “api/src/notes/notes.controller.ts を変更する”
api/src/notes/notes.controller.ts
1
import { Body, Controller, Post } from '@nestjs/common';
1
import {
2
Body,
3
Controller,
4
Get,
5
NotFoundException,
6
Param,
7
Post,
8
} from '@nestjs/common';
2
9
import { randomUUID } from 'node:crypto';
3
10
import type { CreateNoteInput, Note } from '../api/index.js';
4
11
import { openDatabase } from '../database.js';
api/src/notes/notes.controller.ts
24
31
.run(note);
25
32
return note;
26
33
}
34
35
@Get(':id')
36
findOne(@Param('id') id: string): Note {
37
const note = this.db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as
38
Note | undefined;
39
if (!note) {
40
throw new NotFoundException(`Note ${id} not found`);
41
}
42
return note;
43
}
27
44
}
  • @Get(':id') と @Param('id') … URL の :id を引数で受け取ります
  • prepare(...).get(id) … SQL の ? に id を入れて実行し、最初の 1 行を返します。無ければ undefined です
  • NotFoundException … 投げると、NestJS が 404 Not Found の応答にします

npm run start:dev で API を起動したまま、VS Code で api/openapi.yaml を開きます。

  1. post: の Try it でメモを作り、返ってきた id をコピーします
  2. /notes/{id}: の get: の下の Try it を押し、id に貼り付けて Send を押します

作ったメモが 200 で返れば大丈夫です。API を再起動してから送っても返ります(SQLite に残っています)。id の最後の 1 文字を変えて送ると 404 になります。

ID(cf3ba8aa-850c-4fec-bd88-7378c0e88c37)は、作ったメモの ID に置き換えます。

ターミナルウィンドウ
curl -i http://localhost:3000/notes/cf3ba8aa-850c-4fec-bd88-7378c0e88c37

1 行目が HTTP/1.1 200 OK になれば大丈夫です。

この節は、次の公式ドキュメントをもとに書いています。

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

Section titled “この節を終えたときのディレクトリ”
この節を終えた状態をダウンロード