LoginSignup
0
0

prisma × kyselyを使えるように準備しておく

Posted at

利用するまでの手順

  1. 必要なパッケージをインストールする。

    $ npm install prisma --save-dev
    $ npm install @prisma/client
    $ npm install kysely
    
  2. Prismaの初期設定を行う。

    • プロジェクトディレクトリにprismaディレクトリprisma/schema.prismaが作成される。
    $ npx prisma init
    
  3. Prismaスキーマの定義を行う。

    prisma/schema.prisma
    generator client {
      provider = "prisma-client-js"
    }
    
    generator kysely {
      provider = "prisma-kysely"
      output       = "../src/db"
      fileName     = "types.ts"
      enumFileName = "enums.ts"
    }
    
    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    model User {
      id    Int    @id @default(autoincrement())
      name  String
      email String @unique
      posts Post[]
    }
    
    model Post {
      id       Int    @id @default(autoincrement())
      title    String
      content  String?
      authorId Int
      author   User   @relation(fields: [authorId], references: [id])
    }
    
  4. .envに環境変数DATABASE_URLを定義する。

    .env
    DATABASE_URL="postgresql://user:password@localhost:5432/mydatabase"
    
  5. マイグレーションを行う。

    $ npx prisma migrate dev --name init
    
  6. Prismaクライアントを生成する。

    • 型ファイルが生成される。
    $ npx prisma generate
    
  7. prisma-kyselyの設定を行う。

    kysely.ts
    import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
    import { PrismaClient } from '@prisma/client';
    import { Kysely, MysqlDialect } from 'kysely';
    import { createPool } from 'mysql2';
    import { ConfigService } from './config.service';
    import { DB } from './types';
    
    @Injectable()
    export class KyselyService implements OnModuleInit, OnModuleDestroy {
      constructor(private config: ConfigService) {}
    
      private readonly prisma = new PrismaClient();
      private readonly kysely = new Kysely<DB>({
        dialect: new MysqlDialect({
          pool: {
            min: 0,
            max: 10,
          },
        }),
      });
    
      async onModuleInit() {
        await this.prisma.$connect();
      }
    
      async onModuleDestroy() {
        await this.prisma.$disconnect();
      }
    
      getKysely(): Kysely<DB> {
        return this.kysely;
      }
    }
    

参考

Kysely | Kysely
TypeScriptのSQLビルダー Kysely をさわってみた
TypescriptのSQLクエリビルダーのkyselyが快適
TypeScript用クエリービルダー「Kysely」でトランザクション、UPSERT、JOINを使ってみた

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