コンテンツにスキップ

処理をサービスに分ける

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

SQL と処理を サービス に移し、コントローラーは「受け取って、サービスを呼んで、返す」だけにします。データベースは、コントローラーではなくサービスに注入します。

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

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

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

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 {}

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

Section titled “api/src/notes/notes.service.ts を変更する”
api/src/notes/notes.service.ts
1
import { Injectable } from '@nestjs/common';
1
import { Injectable, NotFoundException } from '@nestjs/common';
2
import { randomUUID } from 'node:crypto';
3
import { DatabaseSync } from 'node:sqlite';
4
import type { CreateNoteDto } from './dto/create-note.dto.js';
5
import type { UpdateNoteDto } from './dto/update-note.dto.js';
6
import type { Note } from './entities/note.entity.js';
2
7
3
8
@Injectable()
4
export class NotesService {}
9
export class NotesService {
10
constructor(private readonly db: DatabaseSync) {}
11
12
findAll(): Note[] {
13
return this.db
14
.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.db
28
.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) as
37
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.db
53
.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 を変更する”
api/src/notes/notes.controller.ts
4
4
Delete,
5
5
Get,
6
6
HttpCode,
7
NotFoundException,
8
7
Param,
9
8
Post,
10
9
Put,
11
10
} from '@nestjs/common';
12
import { randomUUID } from 'node:crypto';
13
import { DatabaseSync } from 'node:sqlite';
14
11
import { z } from 'zod';
15
12
import { createNoteSchema, type CreateNoteDto } from './dto/create-note.dto.js';
16
13
import { updateNoteSchema, type UpdateNoteDto } from './dto/update-note.dto.js';
17
14
import type { Note } from './entities/note.entity.js';
15
import { NotesService } from './notes.service.js';
18
16
19
17
/** URL の :id。メモの ID は UUID。 */
20
18
const noteIdSchema = z.uuid();
21
19
22
20
@Controller('notes')
23
21
export class NotesController {
24
constructor(private readonly db: DatabaseSync) {}
22
constructor(private readonly notesService: NotesService) {}
25
23
26
24
@Get()
27
25
findAll(): Note[] {
28
return this.db
29
.prepare('SELECT * FROM notes ORDER BY createdAt')
30
.all() as Note[];
26
return this.notesService.findAll();
31
27
}
32
28
33
29
@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.db
47
.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);
52
32
}
53
33
54
34
@Get(':id')
55
35
findOne(@Param('id', { schema: noteIdSchema }) id: string): Note {
56
const note = this.db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as
57
Note | undefined;
58
if (!note) {
59
throw new NotFoundException(`Note ${id} not found`);
60
}
61
return note;
36
return this.notesService.findOne(id);
62
37
}
63
38
64
39
@Put(':id')
65
40
update(
66
41
@Param('id', { schema: noteIdSchema }) id: string,
67
@Body({ schema: updateNoteSchema })
68
input: UpdateNoteDto,
42
@Body({ schema: updateNoteSchema }) input: UpdateNoteDto,
69
43
): 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.db
78
.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);
83
45
}
84
46
85
47
@Delete(':id')
86
48
@HttpCode(204)
87
49
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);
92
51
}
93
52
}
  • 入力チェック(schema)と応答のステータス(@HttpCode(204))は、HTTP の決まりなのでコントローラーに残します

npm run start:dev で起動したまま、api/openapi.yaml の 5 つの操作を Try it で送ります。04 章の最後と同じ応答(200・201・204・400・404)が返れば、整理しても動きは変わっていません。

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

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

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