0.4.3 • Published 2 days ago

@anchan828/nest-kysely v0.4.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 days ago

@anchan828/nest-kysely

npm NPM

Module for using kysely with nestjs.

Installation

$ npm i --save @anchan828/nest-kysely kysely

Quick Start

1. Import module

import { KyselyModule } from "@anchan828/nest-kysely";
import * as SQLite from "better-sqlite3";

@Module({
  imports: [
    KyselyModule.register({
      dialect: new SqliteDialect({
        database: new SQLite(":memory:"),
      }),
    }),
  ],
})
export class AppModule {}

2. Inject KyselyService

import { KyselyService } from "@anchan828/nest-kysely";
import { Database } from "./database.type";
@Injectable()
export class ExampleService {
  constructor(readonly kysely: KyselyService<Database>) {}

  public async test(): Promise<void> {
    await this.kysely.db.selectFrom("person").where("id", "=", id).selectAll().executeTakeFirst();
  }
}

Migration

If you want to do migration at module initialization time like TypeORM, use the migrations option. This package provides some migration providers.

KyselyMigrationClassProvider

This provider can perform migration by passing the Migration class.

import { Kysely, Migration } from "kysely";
import { KyselyMigrationClassProvider } from "@anchan828/nest-kysely";

class CreateUserTable implements Migration {
  public async up(db: Kysely<any>): Promise<void> {
    await db.schema
      .createTable("user")
      .addColumn("id", "integer", (cb) => cb.primaryKey().autoIncrement().notNull())
      .addColumn("name", "varchar(255)", (cb) => cb.notNull())
      .execute();
  }
}

@Module({
  imports: [
    KyselyModule.register({
      dialect: new SqliteDialect({
        database: new SQLite(":memory:"),
      }),
      migrations: {
        migrationsRun: true,
        migratorProps: {
          provider: new KyselyMigrationClassProvider([CreateUserTable]),
        },
      },
    }),
  ],
})
export class AppModule {}

KyselyMigrationFileProvider

This provider can perform migration by passing the migrations directory path. This provider wraps the FileMigrationProvider provided by kysely and supports SQL files.

migrations
├── 1715003546247-CreateUserTable.ts
├── 1715003558664-CreateUserInsertTrigger.sql
├── 1715003568628-UpdateUserTable.sql
└── 1715003583015-CreateUserTableIndex.js
@Module({
  imports: [
    KyselyModule.register({
      dialect: new PostgresDialect({
        pool: new Pool({
          database: "test",
          user: "root",
          password: "root",
        }),
      }),
      migrations: {
        migrationsRun: true,
        migratorProps: {
          provider: new KyselyMigrationFileProvider({
            fs: require("fs"),
            path: require("path"),
            migrationFolder: path.join(__dirname, "migrations"),
          }),
        },
      },
    }),
  ],
})
export class AppModule {}

KyselyMigrationMergeProvider

This provider can perform migration by merging multiple providers.

@Module({
  imports: [
    KyselyModule.register({
      dialect: new PostgresDialect({
        pool: new Pool({
          database: "test",
          user: "root",
          password: "root",
        }),
      }),
      migrations: {
        migrationsRun: true,
        migratorProps: {
          provider: new KyselyMigrationMergeProvider({
            providers: [
              new KyselyMigrationFileProvider({
                fs: require("fs"),
                path: require("path"),
                migrationFolder: path.join(__dirname, "migrations"),
              }),
              new KyselyMigrationClassProvider([CreateUserTable]),
            ],
          }),
        },
      },
    }),
  ],
})
export class AppModule {}

Transaction

This KyselyTransactional decorator handles and propagates transactions between methods of different providers.

Use @KyselyTransactional()

@Injectable()
class ChildService {
  constructor(private readonly kysely: KyselyService<Database>) {}

  public async ok(): Promise<void> {
    await this.kysely.db.insertInto("user").values({ name: "ChildService" }).execute();
  }
}

@Injectable()
class ParentService {
  constructor(
    private readonly child: ChildService,
    private readonly kysely: KyselyService<Database>,
  ) {}

  @KyselyTransactional()
  public async ok(): Promise<void> {
    await this.kysely.db.insertInto("user").values({ name: "ParentService" }).execute();
    await this.child.ok();
  }
}

Use KyselyService

Using KyselyService.startTransaction allows you to propagate transactions.

@Injectable()
class ChildService {
  constructor(private readonly kysely: KyselyService<Database>) {}

  public async ok(): Promise<void> {
    await this.kysely.db.insertInto("user").values({ name: "ChildService" }).execute();
  }
}

@Injectable()
class ParentService {
  constructor(
    private readonly child: ChildService,
    private readonly kysely: KyselyService<Database>,
  ) {}

  public async ok(): Promise<void> {
    await this.kysely.startTransaction(() => {
      await this.kysely.db.insertInto("user").values({ name: "ParentService" }).execute();
      await this.child.ok();
    });
  }
}

Use raw Kysely object

You can inject Kysely. However, transactions using KyselyTransactional will not work.

@Injectable()
class Service {
  constructor(@Inject(KYSELY) private readonly db: Kysely<Database>) {}

  public async ok(): Promise<void> {
    await this.db.insertInto("user").values({ name: "Service" }).execute();
  }
}

Plugin

RemoveNullPropertyPlugin

This plugin removes properties with null values from the result.

{
  "id": 1,
  "name": "John",
  "nullableColumn": null
}

will be transformed to:

{
  "id": 1,
  "name": "John"
}

CLI

This package provides a very simple CLI for generating migration files.

$ npm exec -- nest-kysely migration:create src/migrations CreateTable
Created migration file: src/migrations/1710847324757-CreateTable.ts

A timestamp is automatically added to the file name and class name.

import { Kysely, Migration } from "kysely";

export class CreateTable1710847324757 implements Migration {
  public async up(db: Kysely<any>): Promise<void> {}
  public async down(db: Kysely<any>): Promise<void> {}
}

Options

OptionDescriptionDefault
--typeType of file (ts/js/sql)ts
--no-downDo not generate down methodfalse

Troubleshooting

Nest can't resolve dependencies of the XXX. Please make sure that the "Symbol(KYSELY_TRANSACTIONAL_DECORATOR_SYMBOL)" property is available in the current context.

This is the error output when using the KyselyTransactional decorator without importing the KyselyModule.

License

MIT

0.4.3

2 days ago

0.4.1

3 days ago

0.4.0

3 days ago

0.4.2

2 days ago

0.3.0

4 days ago

0.2.4

12 days ago

0.2.3

18 days ago

0.2.1

28 days ago

0.2.2

28 days ago

0.2.0

29 days ago

0.1.6

1 month ago

0.1.5

1 month ago

0.1.4

2 months ago

0.1.0

2 months ago

0.1.2

2 months ago

0.1.1

2 months ago

0.1.3

2 months ago

0.0.23

2 months ago

0.0.22

2 months ago

0.0.21

2 months ago

0.0.20

2 months ago

0.0.19

3 months ago

0.0.18

3 months ago

0.0.17

3 months ago

0.0.16

3 months ago

0.0.15

4 months ago

0.0.14

4 months ago

0.0.13

5 months ago

0.0.12

5 months ago

0.0.11

5 months ago

0.0.10

5 months ago

0.0.9

6 months ago

0.0.8

6 months ago

0.0.7

6 months ago

0.0.6

6 months ago

0.0.5

6 months ago

0.0.4

7 months ago

0.0.3

7 months ago

0.0.2

7 months ago

0.0.1

7 months ago