Search code examples
castingpg-promise

Proper way to cast database client to a pg.Client or pg.Pool


I'm using Lucia auth which has adapters for Postgres and node-postgres, but not one specifically for pg-promise. When I try to instantiate the database adapter for Lucia, it complains about the first parameter not being a "Client" or "Pool". After much tinkering, I was able to get it to work declaring it as follows:

import pgPromise from 'pg-promise';
const pgp = pgPromise({});
export const database = pgp(DATABASE_URL_LOCAL);
const adapter = new NodePostgresAdapter(database.$pool as unknown as pg.Pool, {
    user: 'auth_user',
    session: 'user_session'
});

The piece in question is: database.$pool as unknown as pg.Pool. Is this the best way to do this, or is there a cleaner way?


Solution

  • Your usage pattern is correct, there's no better way other than have Lucia add support for pg-promise.

    Inside pg-promise, that pool has type IPool declared internally, which declares only a subset of properties and methods that can be used safely within pg-promise. So when integrating manually like you do, that interface signature is insufficient, and that's why you make it any first, and then recast to the right type.