0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NestJS+Prisma+PostgreSQL+Docker+ESmoduleの環境構築

0
Posted at

はじめに

NestJSの勉強をしていて、
公式ドキュメントがESMに対応していなかったり、
Prismaの導入部分で疑問に思った点があったため、
私なりの解決案を盛り込んだ環境構築の手順です。

実行環境

node v22.12.0
Docker Desktop
prisma 7.8.0

NestJSのインストール

公式ドキュメントの手順に従って進めます。

gitでクローンしてきたディレクトリで環境構築を始める場合は$ nest new .にしてください。

$ npm i -g @nestjs/cli
$ nest new project-name

nest newを実行するとパッケージマネージャーの選択が出てくるので、npmを選択してください。
次に、作成されたpackage.jsonに "type": "module",を追加してください。

package.json
{
  "name": "test",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "type": "module",

また、以下をターミナルで実行してください。

npm install @prisma/adapter-pg
npm install @prisma/client
npm install pg
npm install @nestjs/config

Prismaの設定

$ npm install prisma --save-dev
$ npx prisma
$ npx prisma init

ここまで実行するとルートディレクトリにprisma.config.tsとprismaディレクトリが作成されます。

tsconfig.jsonのcompilerOptionsに以下を追記してください。

tsconfig.json
    "strict": true

次にprisma/schema.prismaの内容を以下のものに設定します。

schema.prisma
generator client {
  provider = "prisma-client-js"
  moduleFormat="esm"
}

datasource db {
  provider = "postgresql"
}

また、prisma.config.tsの内容を以下のように設定してください。

prisma.config.ts
import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});

次に.envファイル中身を以下に変更してください。

.env
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres?schema=public"

Dockerの設定

ここから、prismaを動かしていくためにdockerでdbのサーバーを立てます。

プロジェクトルートから以下のフォルダ、ファイルを作ります。
init.sqlは、データを入れたい人は書いてください。
書かなくても問題ないです。

プロジェクトルート
 └─ docker
    ├── compose.yaml
    ├── image
    │   └── postgres
    │       └── Dockerfile
    └── postgres
        └── init
            └── init.sql
compose.yaml
services:
  postgres:
    container_name: dev-db
    build: ./image/postgres
    restart: always
    ports:
      - "5432:5432"
    volumes:
      - ./postgres/init:/docker-entrypoint-initdb.d
    environment:
      POSTGRES_USER: "postgres"
      POSTGRES_PASSWORD: "postgres"
Dockerfile
FROM postgres:16

ここまで書き終わったら、dockerフォルダに移動し、
ターミナルで以下のコマンドを実行してください。

terminal
docker compose up -d

dockerが起動したか下記コマンドを実行して確認してください。

docker ps

DBの初期化の実行

DBの立ち上げが終わったら、プロジェクトルートに移動してから
ターミナルで以下のコマンドを実行します。

npx prisma migrate dev --name init
npx prisma generate

次にsrcに移動し、以下のコマンドでprisma.service.ts, prisma.module.tsを作成します。

$ nest g service prisma
$ nest g module prisma
$ npm install

prisma.service.tsですが、NestJSのライフサイクルイベントを生かしてサーバー立ち上げ時に、
dbへの接続を完了してからサーバーが立ち上がるようにしました。

prisma.service.ts
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleDestroy, OnModuleInit {
    private pool: Pool;

    constructor(private readonly config: ConfigService) {
        const connectionString = config.get<string>('DATABASE_URL');
        if (!connectionString) {
            throw new Error();
        }
        const pool = new Pool({ connectionString });
        const adapter = new PrismaPg(pool);
        super({ adapter });
        this.pool = pool;
    }
    async onModuleInit() {
        await this.$connect();
    }
    async onModuleDestroy() {
        await this.$disconnect();
        await this.pool.end();
    }
}

こちらのprisma.module.tsをapp.module.tsに追加することで
どのファイルからでもprismaを呼び出すことができるようになります。
@Global()をつければ追加しなくて済みますが、今回はmoduleを追加する形で行います。

prisma.module.ts
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service.js';

@Module({
    providers:[PrismaService],
    exports:[PrismaService]
})

export class PrismaModule {}

onModuleDestoryを活かすためにmain.tsを下記のように修正してください

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableShutdownHooks();

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

.envから環境変数を読み込むためにapp.module.tsを以下に変更してください。

app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller.js';
import { AppService } from './app.service.js';
import { PrismaModule } from './prisma/prisma.module.js';
import { ConfigModule } from '@nestjs/config';


@Module({
  imports: [ConfigModule.forRoot({
      isGlobal:true
    }),
    PrismaModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

サーバー起動について

npm run startなどでサーバーを起動すると以下のようなエラーがおきます。
原因はESMに切り替えたことでimportするファイルに明示的にファイル拡張子を書かないと行けなくなったためです。
手間ですが、エラーが起きた箇所全てに.jsなどのファイル拡張子を追記してください。

terminal
src/app.controller.ts:2:28 
- error TS2307: Cannot find module 
- './app.service' or its corresponding type declarations.

2 import { AppService } from './app.service';

コレで環境構築は完了です。
あとは、適宜コントローラ、サービスを追加して開発を進めてください。

終了するときは以下のコマンドを実行してください。

terminal
docker compose down

おわりに

公式ドキュメントでは、prisma.service.tsをsrc直下に置いているのが疑問でした。
また、ESMに対応していないためにschemaでエラー祭りになったりしたので、コレからNestJSを触る人への一助になると嬉しいです。

NestJSはまだ勉強途中ですが、気が向いたら単体テストについて、
それを使った継続的インテグレーション/継続的デリバリーの構築についても記事を書きたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?