UNPKG

@hirosystems/api-toolkit

Version:
62 lines (61 loc) 2.71 kB
import { AsyncLocalStorage } from 'async_hooks'; import { PgSqlClient } from '.'; /** * AsyncLocalStorage used to determine if the current async context is running inside a SQL * transaction. */ export declare const sqlTransactionContext: AsyncLocalStorage<SqlTransactionContext>; type SqlTransactionContext = { [dbName: string]: PgSqlClient; }; type UnwrapPromiseArray<T> = T extends any[] ? { [k in keyof T]: T[k] extends Promise<infer R> ? R : T[k]; } : T; /** * Base class that provides access to a SQL client and SQL transaction management. */ export declare abstract class BasePgStore { /** * Getter for a SQL client. If used inside `sqlTransaction`, the scoped client within the current * async context will be returned to guarantee transaction consistency. */ get sql(): PgSqlClient; private readonly _sql; constructor(sql: PgSqlClient); close(args?: { timeout?: number; }): Promise<void>; /** * Start a SQL transaction. If any SQL client used within the callback was already scoped inside a * `BEGIN` transaction, no new transaction will be opened. This flexibility allows us to avoid * repeating code while making sure we don't arrive at SQL errors such as * `WARNING: there is already a transaction in progress` which may cause result inconsistencies. * @param callback - Callback with a scoped SQL client * @param readOnly - If a `BEGIN` transaction should be marked as `READ ONLY` * @returns Transaction results */ sqlTransaction<T>(callback: (sql: PgSqlClient) => T | Promise<T>, readOnly?: boolean): Promise<UnwrapPromiseArray<T>>; /** * Start a SQL write transaction. See `sqlTransaction`. * @param callback - Callback with a scoped SQL client * @returns Transaction results */ sqlWriteTransaction<T>(callback: (sql: PgSqlClient) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>; /** * Refreshes a materialized view concurrently depending on the current environment. * @param viewName - Materialized view name */ refreshMaterializedView(viewName: string): Promise<void>; } /** * Base module that extends PgStore functionality and allows organizing queries in separate files. */ export declare abstract class BasePgStoreModule { private readonly parent; constructor(db: BasePgStore); protected get sql(): PgSqlClient; sqlTransaction<T>(callback: (sql: PgSqlClient) => T | Promise<T>, readOnly?: boolean): Promise<UnwrapPromiseArray<T>>; sqlWriteTransaction<T>(callback: (sql: PgSqlClient) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>; refreshMaterializedView(viewName: string): Promise<void>; } export {};