処理をサービスに分ける
SQL と処理(認可の判定も)を サービス に移し、コントローラーは「トークンを確かめて、サービスを呼んで、返す」だけにします。データベースは、コントローラーではなくサービスに注入します。
cd apps/apinpx nest g service notes --no-speccd ../..CREATE src/notes/notes.service.ts (89 bytes)UPDATE src/app.module.ts (484 bytes)AppModule の providers に NotesService が登録されます。
apps/api/src/app.module.ts が変わる
Section titled “apps/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 {}apps/api/src/notes/notes.service.ts を変更する
Section titled “apps/api/src/notes/notes.service.ts を変更する”1import { Injectable } from '@nestjs/common';1import {2 ForbiddenException,3 Injectable,4 NotFoundException,5} from '@nestjs/common';6import type { CognitoAccessTokenPayload } from 'aws-jwt-verify/jwt-model';7import { randomUUID } from 'node:crypto';8import { DatabaseSync } from 'node:sqlite';29
10export type Note = {11 id: string;12 title: string;13 body: string;14 createdAt: string;15 updatedAt: string;16 // 作った人(アクセストークンの sub)。認証を足す前に作ったノートは null17 ownerId: string | null;18 // ノートを分け合うチーム。無ければ null19 teamId: string | null;20};21
322@Injectable()4export class NotesService {}23export class NotesService {24 constructor(private readonly db: DatabaseSync) {}25
26 create(27 input: { title: string; body?: string; teamId?: string },28 ownerId: string,29 ): Note {30 const now = new Date().toISOString();31 const note: Note = {32 id: randomUUID(),33 title: input.title,34 body: input.body ?? '',35 createdAt: now,36 updatedAt: now,37 ownerId,38 teamId: input.teamId ?? null,39 };40 this.db41 .prepare(42 'INSERT INTO notes (id, title, body, createdAt, updatedAt, ownerId, teamId) VALUES (:id, :title, :body, :createdAt, :updatedAt, :ownerId, :teamId)',43 )44 .run(note);45 return note;46 }47
48 findAll(): Note[] {49 return this.db50 .prepare('SELECT * FROM notes ORDER BY createdAt')51 .all() as Note[];52 }53
54 remove(id: string, user: CognitoAccessTokenPayload): void {55 const note = this.db56 .prepare('SELECT ownerId, teamId FROM notes WHERE id = ?')57 .get(id) as Pick<Note, 'ownerId' | 'teamId'> | undefined;58 if (!note) {59 throw new NotFoundException(`Note ${id} not found`);60 }61 // admin グループの人は、だれのノートでも消せる62 const isAdmin = user['cognito:groups']?.includes('admin') ?? false;63 // ノートのチームに入っている人も消せる。所属は team_members の表で確かめる64 const isMember =65 note.teamId !== null &&66 this.db67 .prepare('SELECT 1 FROM team_members WHERE teamId = ? AND userId = ?')68 .get(note.teamId, user.sub) !== undefined;69 // 作った人でも、admin でも、同じチームの人でもなければ 40370 if (note.ownerId !== user.sub && !isAdmin && !isMember) {71 throw new ForbiddenException();72 }73 this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);74 }75}- メソッドの中身は、コントローラーにあったものをそのまま移しています。作った人の ID と、トークンの中身(
user)は、引数で受け取ります - 認可(作った人・
admin・同じチーム)は、消すノートのownerId・teamIdを読んでから決めるので、ノートを読むサービスに置きます - データベースは、サービスのコンストラクターで受け取ります
apps/api/src/notes/notes.controller.ts を変更する
Section titled “apps/api/src/notes/notes.controller.ts を変更する”22 Body,33 Controller,44 Delete,5 ForbiddenException,65 Get,76 Headers,87 HttpCode,9 NotFoundException,108 Param,119 Post,1210} from '@nestjs/common';13import { randomUUID } from 'node:crypto';14import { DatabaseSync } from 'node:sqlite';1511import { verifyToken } from '../auth/verify-token.js';12import { type Note, NotesService } from './notes.service.js';1613
17type Note = {18 id: string;19 title: string;20 body: string;21 createdAt: string;22 updatedAt: string;23 // 作った人(アクセストークンの sub)。認証を足す前に作ったノートは null24 ownerId: string | null;25 // ノートを分け合うチーム。無ければ null26 teamId: string | null;27};28
2914@Controller('notes')3015export class NotesController {31 constructor(private readonly db: DatabaseSync) {}16 constructor(private readonly notesService: NotesService) {}3217
3318 @Post()3419 async create(3722): Promise<Note> {3823 // 正しいアクセストークンが無ければ、ここで 401 になる。あれば、トークンの中身が返る3924 const user = await verifyToken(authorization);40 const now = new Date().toISOString();41 const note: Note = {42 id: randomUUID(),43 title: input.title,44 body: input.body ?? '',45 createdAt: now,46 updatedAt: now,47 // 作った人は、アクセストークンの sub(ユーザーの ID)48 ownerId: user.sub,49 teamId: input.teamId ?? null,50 };51 this.db52 .prepare(53 'INSERT INTO notes (id, title, body, createdAt, updatedAt, ownerId, teamId) VALUES (:id, :title, :body, :createdAt, :updatedAt, :ownerId, :teamId)',54 )55 .run(note);56 return note;25 return this.notesService.create(input, user.sub);5726}5827
5928@Get()6029findAll(): Note[] {61 return this.db62 .prepare('SELECT * FROM notes ORDER BY createdAt')63 .all() as Note[];30 return this.notesService.findAll();6431}6532
6633@Delete(':id')7037 @Param('id') id: string,7138 ): Promise<void> {7239 const user = await verifyToken(authorization);73 const note = this.db74 .prepare('SELECT ownerId, teamId FROM notes WHERE id = ?')75 .get(id) as Pick<Note, 'ownerId' | 'teamId'> | undefined;76 if (!note) {77 throw new NotFoundException(`Note ${id} not found`);78 }79 // admin グループの人は、だれのノートでも消せる80 const isAdmin = user['cognito:groups']?.includes('admin') ?? false;81 // ノートのチームに入っている人も消せる。所属は team_members の表で確かめる82 const isMember =83 note.teamId !== null &&84 this.db85 .prepare('SELECT 1 FROM team_members WHERE teamId = ? AND userId = ?')86 .get(note.teamId, user.sub) !== undefined;87 // 作った人でも、admin でも、同じチームの人でもなければ 40388 if (note.ownerId !== user.sub && !isAdmin && !isMember) {89 throw new ForbiddenException();90 }91 this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);40 this.notesService.remove(id, user);9241 }9342}- トークンの確認(
verifyToken)と応答のステータス(@HttpCode(204))は、HTTP の決まりなのでコントローラーに残します
動作確認する
Section titled “動作確認する”podman compose up -d --build --wait で作り直して起動し、06 章の最後と同じように curl で送ります。alice が作ったノートに対して、次のとおりになれば、整理しても動きは変わっていません。
| 呼び出し | 返るもの |
|---|---|
| トークン無しで作る | 401 |
| alice のトークンで作る | 201 |
| bob のトークンで消す(チームの無いノート) | 403 |
| admin のトークンで消す | 204 |
bob のトークンで消す(bob が入っている team-a のノート) |
204 |
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- NestJS: Providers … サービス(
@Injectable())と依存性の注入