0.7.9 • Published 9 months ago

@anchan828/nest-kysely v0.7.9

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months 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

Repeatable Migrations

This is a feature to support migrations that need to be regenerated multiple times, such as views/functions/triggers/etc. Unlike migrations that are executed only once, it compares the checksum of the SQL to be executed to determine the need for migration.

KyselyModule.register({
  dialect: createDialect(),
  repeatableMigrations: {
    migrationsRun: true,
    migratorProps: {
      provider: new KyselyRepeatableMigrationSqlFileProvider({
        sqlFiles: [resolve(__dirname, "user-view.sql")],
        sqlTexts: [{ name: "test", sql: "SELECT 1;" }],
      }),
    },
  },
});
namehashtimestamp
user-view6c7e36422f79696602e19079534b40762024-05-11T17:04:20.211Z
teste7d6c7d4d9b1b0b4c7f5d7b3d5e9d4d42024-05-11T17:04:20.211Z

Note

  • Once the file is renamed, the migration is executed even if the contents have not changed.
  • Views/Functions/Triggers created by Repeatable Migration are not automatically deleted (or update/rename) by simply deleting the corresponding SQL, so please delete them using the normal migration function.

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.7.9

9 months ago

0.7.8

9 months ago

0.7.6

9 months ago

0.7.5

10 months ago

0.7.7

9 months ago

0.7.2

10 months ago

0.7.1

10 months ago

0.7.4

10 months ago

0.7.3

10 months ago

0.7.0

10 months ago

0.6.5

11 months ago

0.5.10

1 year ago

0.5.11

1 year ago

0.5.14

12 months ago

0.5.12

12 months ago

0.5.13

12 months ago

0.5.4

1 year ago

0.5.6

1 year ago

0.5.5

1 year ago

0.5.8

1 year ago

0.5.7

1 year ago

0.5.9

1 year ago

0.6.3

11 months ago

0.6.2

11 months ago

0.6.4

11 months ago

0.6.1

11 months ago

0.6.0

11 months ago

0.5.3

1 year ago

0.5.2

1 year ago

0.5.0

1 year ago

0.5.1

1 year ago

0.4.3

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.4.2

1 year ago

0.3.0

1 year ago

0.2.4

1 year ago

0.2.3

1 year ago

0.2.1

1 year ago

0.2.2

1 year ago

0.2.0

1 year ago

0.1.6

1 year ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.0

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.3

1 year ago

0.0.23

1 year ago

0.0.22

1 year ago

0.0.21

1 year ago

0.0.20

1 year ago

0.0.19

1 year ago

0.0.18

1 year ago

0.0.17

1 year ago

0.0.16

1 year ago

0.0.15

1 year ago

0.0.14

2 years ago

0.0.13

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago