KyselyK
Kysely3y ago
9 replies
virk

Guidance to create a generic wrapper over Kysely

I am trying to create a generic authentication wrapper over Kysely. The idea is

- You can pass some config to this function, which includes a reference to
Kysely
instance, a database table name and an array of column names.
- The function will return an authenticator instance you can use to perform user lookups during Login. The internals of this function are not important for this discussion.

This is what I have so far. You can copy/paste the following code to run it yourself.

import { Pool } from 'pg'
import { AnyColumn, ColumnType, Generated, Kysely, PostgresDialect } from 'kysely'

/**
 * Interfaces for the table and the database
 */
interface UserTable {
  id: Generated<number>
  email: string
  username: string
  password: string
  created_at: ColumnType<Date, string | undefined, never>
}
interface Database {
  users: UserTable
}

/**
 * PostgreSQL dialect and kysely instance
 */
const dialect = new PostgresDialect({ pool: new Pool(poolConfig) })
const db = new Kysely<Database>({ dialect })

/**
 * Authenticator function that need kysely instance
 * and an unknown table + columns
 */
function createAuthenticator<
  DB,
  TB extends keyof DB & string,
  Columns extends AnyColumn<DB, TB>
>(config: {
  db: Kysely<DB>
  table: TB,
  uids: Columns[]
}) {
  config
      .db
      .selectFrom(config.table)
      // The where clause gives an error
      .where(config.uids[0], '=', 'foobar')
}

/**
 * Using function to create authenticator
 */
createAuthenticator({
  db: db,
  table: 'users',
  uids: ['email'],
})


The
.where(config.uids[0])
method call gives a type error saying, "The Columns are not assignable to the input accepted by the where method".

So, I need some guidance on which approach to take for this use case.
Was this page helpful?