Kysely TypeSafe Query Builder

Build fully typed SQL with Kysely, from typed table definitions through dynamic where clauses to exactly shaped result row types.

TypescriptNodeData Integrity

Code

snippet
import { Kysely, PostgresDialect, Generated, sql } from 'kysely';
import { Pool } from 'pg';

interface Database {
  articles: {
    id: Generated<number>;
    title: string;
    authorId: number;
    published: boolean;
  };
  authors: {
    id: Generated<number>;
    name: string;
  };
}

const db = new Kysely<Database>({
  dialect: new PostgresDialect({
    pool: new Pool({ connectionString: process.env.DATABASE_URL }),
  }),
});

type Filter = { author?: string; onlyPublished?: boolean };

async function searchArticles(filter: Filter) {
  let query = db
    .selectFrom('articles')
    .innerJoin('authors', 'authors.id', 'articles.authorId')
    .select(['articles.id', 'articles.title', 'authors.name as author']);

  if (filter.author !== undefined) {
    query = query.where('authors.name', '=', filter.author);
  }
  if (filter.onlyPublished) {
    query = query.where('articles.published', '=', true);
  }

  const rows = await query
    .orderBy('articles.id', 'desc')
    .limit(25)
    .execute();

  return rows;
}

const fresh = await searchArticles({ onlyPublished: true });
console.log('typed author column:', fresh[0]?.author.length ?? 0);
await db.destroy();