UNPKG

@jadejr/kysely-pglite

Version:

Kysely dialect for @electric-sql/pglite (temporary fork https://github.com/dnlsandiego/kysely-pglite)

65 lines 2.19 kB
import { Repeater } from '@repeaterjs/repeater'; import { assertString } from '@sindresorhus/is'; /** * Wrapper for PGlite's Live Queries extension * @example * const pglive = new KyselyLive(pglite) * const query = db * .selectFrom('sales') * .select(['id', 'price']) * .orderBy((eb) => eb.fn('rand')) * const liveQuery = pglive.query(query) * * for await (const data of liveQuery.subscribe) { * const [sale] = data * console.log(sale.id, sale.price) } */ export class KyselyLive { live; constructor(pglite) { this.live = pglite.live; } query(builder) { const { sql, parameters } = builder.compile(); return this.createLiveRepeater((push) => { return this.live.query(sql, [...parameters], (data) => push(data.rows)); }); } changes(builder, ref) { const { sql, parameters } = builder.compile(); assertString(ref, '`changes` received invalid key'); return this.createLiveRepeater((push) => { return this.live.changes(sql, [...parameters], ref, (data) => push(data)); }); } incrementalQuery(builder, ref) { const { sql, parameters } = builder.compile(); assertString(ref, '`incrementalQuery` received invalid key'); return this.createLiveRepeater((push) => { return this.live.incrementalQuery(sql, [...parameters], ref, (data) => push(data.rows)); }); } createLiveRepeater(liveMethod) { let refresh; let unsubscribe; const subscribe = new Repeater(async (push, stop) => { const res = await liveMethod((data) => push(data)); refresh = res.refresh; unsubscribe = res.unsubscribe; await stop; /** * This will be reached if: * - a `break` statement is used in a `forof await` loop * - an error is thrown inside the `forof await` loop */ res.unsubscribe(); }); return { subscribe, refresh: () => refresh?.(), unsubscribe: () => unsubscribe?.(), }; } } //# sourceMappingURL=kysely-live.js.map