Skip to content

Package

plugin-kysely-postgres v0.8.0

Changelog

seedcordseedcord

The whole Discord bot, typed end to end

Website · Guide · Reference · Discord

npm node bun license

About

@seedcord/plugin-kysely-postgres connects a seedcord bot to Postgres through Kysely. It opens a connection pool when the bot starts, runs your migrations, loads your service classes, and closes the pool when the bot shuts down. Handlers can reach each service through this.core. You declare your database schema once, and Kysely types every query from it.

Install it when your bot stores data in Postgres. It works with a gateway bot and with an http bot on your own server. On a Cloudflare Workers bot, attaching it is a compile error.

seedcord is pre-1.0, so a minor version can break your bot. Each release's changelog says what changed and how to update.

Installation

pnpm add @seedcord/plugin-kysely-postgres kysely pg

Usage

Attach the plugin in bot.ts. Read it from this.core in a handler, under the key you pass:

// bot.ts
import { Seedcord } from '@seedcord/gateway';
import { KyselyPostgres } from '@seedcord/plugin-kysely-postgres';
import { GatewayIntentBits } from 'discord.js';
import { Converters, Envapter } from 'envapt';

export default new Seedcord({
    bot: {
        clientOptions: { intents: [GatewayIntentBits.Guilds] },
        interactions: { path: './handlers' },
        commands: { path: './commands' },
        events: { path: null }
    },
    subscribers: { path: null }
}).attach('sql', KyselyPostgres, {
    dir: './services',
    connectionString: Envapter.getRequired('DATABASE_URL', Converters.String),
    migrations: { dir: './migrations' }
});

Each file in services/ holds a service for one table. Database is the table interface you write for Kysely:

// services/Users.ts
import { KyselyService, RegisterKyselyService } from '@seedcord/plugin-kysely-postgres';

import type { Database } from '../database';

@RegisterKyselyService('users')
export class Users extends KyselyService<'users'> {
    public async findByUserId(userId: string) {
        return this.db.selectFrom(this.table).selectAll().where('user_id', '=', userId).executeTakeFirst();
    }
}

declare module '@seedcord/plugin-kysely-postgres' {
    interface KyselyDatabase {
        schema: Database;
    }
}

Run seedcord codegen after you add or rename a service. It adds the service's key to KyselyServices, the type behind the decorator and core.sql.services. Then call await this.core.sql.services.users.findByUserId(this.user.id) from a handler. The Kysely guide covers the options, the schema, services, and migrations.