処理をサービスに分ける
SQL と処理を サービス に移し、コントローラーは「受け取って、サービスを呼んで、返す」だけにします。データベースは、コントローラーではなくサービスに注入します。
npx nest g service notes --no-specCREATE src/notes/notes.service.ts (89 bytes)UPDATE src/app.module.ts (484 bytes)AppModule の providers に NotesService が登録されます。
api/src/app.module.ts が変わる
Section titled “api/src/app.module.ts が変わる”33import { AppService } from './app.service.js';44import { NotesController } from './notes/notes.controller.js';55import { DatabaseModule } from './database/database.module.js';6import { NotesService } from './notes/notes.service.js';67
78@Module({89 imports: [DatabaseModule],910 controllers: [AppController, NotesController],10 providers: [AppService],11 providers: [AppService, NotesService],1112})1213export class AppModule {}api/src/notes/notes.service.ts を変更する
Section titled “api/src/notes/notes.service.ts を変更する”1import { Injectable } from '@nestjs/common';1import { Injectable, NotFoundException } from '@nestjs/common';2import { randomUUID } from 'node:crypto';3import { DatabaseSync } from 'node:sqlite';4import type { CreateNoteDto } from './dto/create-note.dto.js';5import type { UpdateNoteDto } from './dto/update-note.dto.js';6import type { Note } from './entities/note.entity.js';27
38@Injectable()4export class NotesService {}9export class NotesService {10 constructor(private readonly db: DatabaseSync) {}11
12 findAll(): Note[] {13 return this.db14 .prepare('SELECT * FROM notes ORDER BY createdAt')15 .all() as Note[];16 }17
18 create(input: CreateNoteDto): Note {19 const now = new Date().toISOString();20 const note: Note = {21 id: randomUUID(),22 title: input.title,23 body: input.body,24 createdAt: now,25 updatedAt: now,26 };27 this.db28 .prepare(29 'INSERT INTO notes (id, title, body, createdAt, updatedAt) VALUES (:id, :title, :body, :createdAt, :updatedAt)',30 )31 .run(note);32 return note;33 }34
35 findOne(id: string): Note {36 const note = this.db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as37 Note | undefined;38 if (!note) {39 throw new NotFoundException(`Note ${id} not found`);40 }41 return note;42 }43
44 update(id: string, input: UpdateNoteDto): Note {45 const note = this.findOne(id);46 const updated: Note = {47 ...note,48 title: input.title,49 body: input.body,50 updatedAt: new Date().toISOString(),51 };52 this.db53 .prepare(54 'UPDATE notes SET title = ?, body = ?, updatedAt = ? WHERE id = ?',55 )56 .run(updated.title, updated.body, updated.updatedAt, id);57 return updated;58 }59
60 remove(id: string): void {61 const result = this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);62 if (result.changes === 0) {63 throw new NotFoundException(`Note ${id} not found`);64 }65 }66}- メソッドの中身は、コントローラーにあったものをそのまま移しています
- データベースは、サービスのコンストラクターで受け取ります
api/src/notes/notes.controller.ts を変更する
Section titled “api/src/notes/notes.controller.ts を変更する”44 Delete,55 Get,66 HttpCode,7 NotFoundException,87 Param,98 Post,109 Put,1110} from '@nestjs/common';12import { randomUUID } from 'node:crypto';13import { DatabaseSync } from 'node:sqlite';1411import { z } from 'zod';1512import { createNoteSchema, type CreateNoteDto } from './dto/create-note.dto.js';1613import { updateNoteSchema, type UpdateNoteDto } from './dto/update-note.dto.js';1714import type { Note } from './entities/note.entity.js';15import { NotesService } from './notes.service.js';1816
1917/** URL の :id。メモの ID は UUID。 */2018const noteIdSchema = z.uuid();2119
2220@Controller('notes')2321export class NotesController {24 constructor(private readonly db: DatabaseSync) {}22 constructor(private readonly notesService: NotesService) {}2523
2624 @Get()2725 findAll(): Note[] {28 return this.db29 .prepare('SELECT * FROM notes ORDER BY createdAt')30 .all() as Note[];26 return this.notesService.findAll();3127 }3228
3329 @Post()34 create(35 @Body({ schema: createNoteSchema })36 input: CreateNoteDto,37 ): Note {38 const now = new Date().toISOString();39 const note: Note = {40 id: randomUUID(),41 title: input.title,42 body: input.body,43 createdAt: now,44 updatedAt: now,45 };46 this.db47 .prepare(48 'INSERT INTO notes (id, title, body, createdAt, updatedAt) VALUES (:id, :title, :body, :createdAt, :updatedAt)',49 )50 .run(note);51 return note;30 create(@Body({ schema: createNoteSchema }) input: CreateNoteDto): Note {31 return this.notesService.create(input);5232 }5333
5434 @Get(':id')5535 findOne(@Param('id', { schema: noteIdSchema }) id: string): Note {56 const note = this.db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as57 Note | undefined;58 if (!note) {59 throw new NotFoundException(`Note ${id} not found`);60 }61 return note;36 return this.notesService.findOne(id);6237 }6338
6439 @Put(':id')6540 update(6641 @Param('id', { schema: noteIdSchema }) id: string,67 @Body({ schema: updateNoteSchema })68 input: UpdateNoteDto,42 @Body({ schema: updateNoteSchema }) input: UpdateNoteDto,6943 ): Note {70 const note = this.findOne(id);71 const updated: Note = {72 ...note,73 title: input.title,74 body: input.body,75 updatedAt: new Date().toISOString(),76 };77 this.db78 .prepare(79 'UPDATE notes SET title = ?, body = ?, updatedAt = ? WHERE id = ?',80 )81 .run(updated.title, updated.body, updated.updatedAt, id);82 return updated;44 return this.notesService.update(id, input);8345 }8446
8547 @Delete(':id')8648 @HttpCode(204)8749 remove(@Param('id', { schema: noteIdSchema }) id: string): void {88 const result = this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);89 if (result.changes === 0) {90 throw new NotFoundException(`Note ${id} not found`);91 }50 this.notesService.remove(id);9251 }9352}- 入力チェック(
schema)と応答のステータス(@HttpCode(204))は、HTTP の決まりなのでコントローラーに残します
動作確認する
Section titled “動作確認する”npm run start:dev で起動したまま、api/openapi.yaml の 5 つの操作を Try it で送ります。04 章の最後と同じ応答(200・201・204・400・404)が返れば、整理しても動きは変わっていません。
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- NestJS: Providers … サービス(
@Injectable())と依存性の注入