Nest.js TypeORM(SQLite)でデータを取得して返す

November 3, 2021

引き続きNest.jsを触っています。 今回はSQLiteからデータを取得して一覧を返すところ。

DB設定

1
$ npm install --save @nestjs/typeorm typeorm sqlite3
1
2
3
4
5
6
7
8
9
10
11
12
# ormconfig.json 

{
  "type": "sqlite",
  "database": "data/dev.sqlite3",
  "entities": [
    "dist/entities/**/*.entity.js"
  ],
  "migrations": [
    "dist/migrations/**/*.js"
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# src/app.module.ts

 import { Module } from '@nestjs/common';
 import { AppController } from './app.controller';
 import { AppService } from './app.service';
+import { TypeOrmModule } from '@nestjs/typeorm';
 
 @Module({
-  imports: [],
-  controllers: [AppController],
+  imports: [TypeOrmModule.forRoot()],
+  controllers: [AppController],
   providers: [AppService],
 })
 export class AppModule {}

マイグレーション

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# src/entities/post.entity.ts 

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  readonly id: number;

  @Column()
  title: string;

  @Column('text')
  content: string;

  @CreateDateColumn()
  readonly createdAt?: Date;

  @UpdateDateColumn()
  readonly updatedAt?: Date;
}
1
2
3
4
# package.json

+    "db:generate": "npm run build; typeorm migration:generate -d src/migrations",
+    "db:migrate": "npm run build; typeorm migration:run"
1
2
$ npm run db:generate -- -n CreatePost
$ npm run db:migrate

Post一覧API

1
2
3
$ nest g module posts
$ nest g controller posts
$ nest g service posts

nest g を実行すると app.module.ts にも自動で追記される。

生成されたファイルを修正。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# src/posts/posts.module.ts 

import { Module } from '@nestjs/common';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
import { Post } from 'src/entities/post.entity';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forFeature([Post])],
  controllers: [PostsController],
  providers: [PostsService],
})
export class PostsModule {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# posts.controller.ts 

import { Controller, Get } from '@nestjs/common';
import { PostsService } from './posts.service';

@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @Get()
  async findAll() {
    return await this.postsService.findAll();
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# src/posts/posts.service.ts 

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from '../entities/post.entity';

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(Post)
    private readonly postRepository: Repository<Post>,
  ) {}

  async findAll() {
    return await this.postRepository.find();
  }
}

動作確認

1
2
3
4
5
6
$ sqlite3 data/dev.sqlite3 
sqlite> INSERT INTO post VALUES(NULL, 'title', 'content', datetime('now'), datetime('now'));
sqlite> .exit

$ curl http://localhost:3000/posts
[{"id":1,"title":"title","content":"content","createdAt":"2021-11-03T13:30:52.000Z","updatedAt":"2021-11-03T13:30:52.000Z"}]

動いた。

テストのエラーを解消

TypeORMを入れるとposts関連のテストが通らなくなるので、修正。

1
2
3
4
5
6
7
8
9
      providers: [
        PostsService,
        {
          provide: getRepositoryToken(Post),
          useValue: {
            find: () => [],
          },
        },
      ],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ npm test 

> nest-blog@0.0.1 test
> jest

 PASS  src/app.controller.spec.ts (7.21 s)
 PASS  src/posts/posts.service.spec.ts (7.879 s)
 PASS  src/posts/posts.controller.spec.ts (7.971 s)

Test Suites: 3 passed, 3 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        8.461 s
Ran all test suites.

こうすることで通ったが、他にもやり方はありそう。

参考