コンテンツにスキップ

処理をサービスに分ける

07 章 処理をサービスに分ける

SQL と処理(認可の判定も)を サービス に移し、コントローラーは「トークンを確かめて、サービスを呼んで、返す」だけにします。データベースは、コントローラーではなくサービスに注入します。

SQL と処理が NotesService に分かれる。DatabaseSync は NotesService に、NotesService は NotesController に注入される

ターミナルウィンドウ
cd apps/api
npx nest g service notes --no-spec
cd ../..
CREATE src/notes/notes.service.ts (89 bytes)
UPDATE src/app.module.ts (484 bytes)

AppModule の providers に NotesService が登録されます。

apps/api/src/app.module.ts
3
3
import { AppService } from './app.service.js';
4
4
import { NotesController } from './notes/notes.controller.js';
5
5
import { DatabaseModule } from './database/database.module.js';
6
import { NotesService } from './notes/notes.service.js';
6
7
7
8
@Module({
8
9
imports: [DatabaseModule],
9
10
controllers: [AppController, NotesController],
10
providers: [AppService],
11
providers: [AppService, NotesService],
11
12
})
12
13
export class AppModule {}

apps/api/src/notes/notes.service.ts を変更する

Section titled “apps/api/src/notes/notes.service.ts を変更する”
apps/api/src/notes/notes.service.ts
1
import { Injectable } from '@nestjs/common';
1
import {
2
ForbiddenException,
3
Injectable,
4
NotFoundException,
5
} from '@nestjs/common';
6
import type { CognitoAccessTokenPayload } from 'aws-jwt-verify/jwt-model';
7
import { randomUUID } from 'node:crypto';
8
import { DatabaseSync } from 'node:sqlite';
2
9
10
export type Note = {
11
id: string;
12
title: string;
13
body: string;
14
createdAt: string;
15
updatedAt: string;
16
// 作った人(アクセストークンの sub)。認証を足す前に作ったノートは null
17
ownerId: string | null;
18
// ノートを分け合うチーム。無ければ null
19
teamId: string | null;
20
};
21
3
22
@Injectable()
4
export class NotesService {}
23
export 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.db
41
.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.db
50
.prepare('SELECT * FROM notes ORDER BY createdAt')
51
.all() as Note[];
52
}
53
54
remove(id: string, user: CognitoAccessTokenPayload): void {
55
const note = this.db
56
.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.db
67
.prepare('SELECT 1 FROM team_members WHERE teamId = ? AND userId = ?')
68
.get(note.teamId, user.sub) !== undefined;
69
// 作った人でも、admin でも、同じチームの人でもなければ 403
70
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 を変更する”
apps/api/src/notes/notes.controller.ts
2
2
Body,
3
3
Controller,
4
4
Delete,
5
ForbiddenException,
6
5
Get,
7
6
Headers,
8
7
HttpCode,
9
NotFoundException,
10
8
Param,
11
9
Post,
12
10
} from '@nestjs/common';
13
import { randomUUID } from 'node:crypto';
14
import { DatabaseSync } from 'node:sqlite';
15
11
import { verifyToken } from '../auth/verify-token.js';
12
import { type Note, NotesService } from './notes.service.js';
16
13
17
type Note = {
18
id: string;
19
title: string;
20
body: string;
21
createdAt: string;
22
updatedAt: string;
23
// 作った人(アクセストークンの sub)。認証を足す前に作ったノートは null
24
ownerId: string | null;
25
// ノートを分け合うチーム。無ければ null
26
teamId: string | null;
27
};
28
29
14
@Controller('notes')
30
15
export class NotesController {
31
constructor(private readonly db: DatabaseSync) {}
16
constructor(private readonly notesService: NotesService) {}
32
17
33
18
@Post()
34
19
async create(
apps/api/src/notes/notes.controller.ts
37
22
): Promise<Note> {
38
23
// 正しいアクセストークンが無ければ、ここで 401 になる。あれば、トークンの中身が返る
39
24
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.db
52
.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);
57
26
}
58
27
59
28
@Get()
60
29
findAll(): Note[] {
61
return this.db
62
.prepare('SELECT * FROM notes ORDER BY createdAt')
63
.all() as Note[];
30
return this.notesService.findAll();
64
31
}
65
32
66
33
@Delete(':id')
apps/api/src/notes/notes.controller.ts
70
37
@Param('id') id: string,
71
38
): Promise<void> {
72
39
const user = await verifyToken(authorization);
73
const note = this.db
74
.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.db
85
.prepare('SELECT 1 FROM team_members WHERE teamId = ? AND userId = ?')
86
.get(note.teamId, user.sub) !== undefined;
87
// 作った人でも、admin でも、同じチームの人でもなければ 403
88
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);
92
41
}
93
42
}
  • トークンの確認(verifyToken)と応答のステータス(@HttpCode(204))は、HTTP の決まりなのでコントローラーに残します

podman compose up -d --build --wait で作り直して起動し、06 章の最後と同じように curl で送ります。alice が作ったノートに対して、次のとおりになれば、整理しても動きは変わっていません。

呼び出し 返るもの
トークン無しで作る 401
alice のトークンで作る 201
bob のトークンで消す(チームの無いノート) 403
admin のトークンで消す 204
bob のトークンで消す(bob が入っている team-a のノート) 204

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

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

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