/** * The top-level Verse object and related types. * * @packageDocumentation */ import { List } from "immutable"; import { Convention } from "./conventions/convention.js"; import { Driver, IsolationLevel } from "./db/driver.js"; import { InheritanceStrategy } from "./inheritance/strategy.js"; import { FromClass, UnwrapProperties } from "./model/builder.js"; import { EntityModel, Model, ValueObjectModel } from "./model/model.js"; import { AsyncQueryable, AsyncSequence, Queryable } from "./query/queryable.js"; import { UnitOfWorkApi } from "./uow.js"; import { Logger } from "./utils/logging.js"; import { Unbrand } from "./utils/utils.js"; /** * An object specifying runtime configuration information like the database driver, * logger, and default transaction isolation level. * * @example * const config = { * driver: new PostgresDriver(), * logger: new ConsoleLogger(), * } * * const db = verse({ * config, * { * // model definition... * } * }); */ export type Config = { /** * The database driver. */ readonly driver: Driver; /** * A logger instance. */ readonly logger?: Logger; /** * The default transaction isolation level. */ readonly isolation?: IsolationLevel | undefined; /** * An optional function that allows you to add or customize conventions. */ readonly conventions?: ((conventions: Convention[]) => Convention[]) | undefined; }; /** * A metadata object containing the configuration, model, and inheritance strategy. */ export type Metadata = { /** * The runtime configuration. */ config: Config; /** * The metadata model. */ model: Model; /** * The inheritance strategy. */ inheritance: InheritanceStrategy; }; /** * A type that can infer an entity type from an {@link EntityModel} when used in conjunction with * the _typeof_ operator. * * @example * const db = verse({ * config: // ... * model: { * entities: { * customers: entity( * // ... * ) * }, * }, * }); * * type Customer = EntityType; */ export type EntityType = Model extends EntityModel ? UnwrapProperties : never; export type ValueObjectType = Model extends ValueObjectModel ? UnwrapProperties : never; /** * Settings that affect the behaviour of individual queries, such as disabling default entity * query conditions. Used in conjunction with the {@link RootQueryOperations.options} query operator. */ export type QueryOptions = { /** * Disables entity query conditions for the query. * * @example * // Disable the default "soft delete" condition for the query. * const q = * db.from.products.options({ disabledConditions: ["soft delete"] }); */ disabledConditions?: "all" | readonly string[]; }; /** * Compiled query operators. * * See {@link Queryable} for a list of available query operators. */ export type From = { [Key in keyof TEntities]: Queryable> & RootQueryOperations>>; }; /** * Non-compiled query operators. * * See {@link AsyncQueryable} for a list of available query operators. */ export type AsyncFrom = { [Key in keyof TEntities]: AsyncQueryable, TEntities> & RootQueryOperations, TEntities>>; }; export type RootQueryOperations = { /** * Inject a raw SQL query using tagged template literals. The returned queryable may be further * composed with additional query operators. * * @example * const id = 1; * const album = * db.from.albums * .sql`select * from "Album" where "AlbumId" = ${id}`.single(); * * @param strings The SQL query template string. * @param values The values to be inserted into the query. * @returns The queryable result of the injected SQL query. */ sql(strings: TemplateStringsArray, ...values: readonly any[]): TQueryable; /** * Set query options that affect the behaviour of the query. * * @example * const q = * db.from.albums.options({ disabledConditions: ["soft delete"] }); * * @param options The query options. * @returns The queryable with the specified options applied. */ options(options: QueryOptions): TQueryable; }; /** * Strongly-typed entity unit of work add/remove functions. */ export type EntitySet = { /** * Adds one or more entities to the current unit of work. The entities will be tracked in the * `added` {@link EntityState} and will be inserted into the database when the unit of work is * committed. * * @param entities The entities to be added to the unit of work. * @returns A promise that resolves when the entities have been successfully * added to the unit of work. */ add(...entities: readonly (T extends FromClass ? Unbrand : Partial)[]): Promise; /** * Removes one or more entities from the current unit of work. The entities will be tracked in the * `removed` {@link EntityState} and will be deleted from the database when the unit of work is * committed. * * @param entities The entities to be removed from the unit of work. */ remove(...entities: readonly Unbrand[]): void; }; /** * Extracts the object type from an {@link EntityModel}. */ export type EntityObject = Model extends EntityModel ? Object : never; /** * Labelled access to strongly-typed entity query and unit of work operations. */ export type EntitySets = { [Key in keyof TEntities]: AsyncQueryable, TEntities> & EntitySet> & RootQueryOperations, TEntities>>; }; /** * The full unit of work API. */ export type UnitOfWork = UnitOfWorkApi & EntitySets; /** * The result of a query execution. */ export type QueryResult = T extends Queryable ? AsyncSequence : Promise; /** * An object containing labelled {@link EntityModel} configuration objects. */ export type Entities = { [K: string]: EntityModel; }; /** * An object containing entity and value-object configuration. */ export type ModelBuilder = { /** * One or more labelled entity models. */ entities: TEntities; /** * Zero or more value objects models. */ values?: readonly ValueObjectModel[]; }; /** * The top-level Verse object. * * See {@link verse} for detailed usage information. */ export declare class Verse { #private; readonly config: Config; /** * Provides methods to perform various operations on the database. */ readonly database: DbOperations; /** * Provides access to strongly-typed entity query operations. */ readonly from: AsyncFrom; /** * The metadata object containing the configuration, model, and inheritance strategy. */ readonly metadata: Metadata; /** * The labelled entity models. Enables easy use of {@link EntityType} with `typeof` * from the root verse instance. */ readonly entities: TEntities; /** * Creates a new instance. * * @param config The configuration object. * @param builder The model builder object. */ constructor(config: Config, builder: ModelBuilder); /** * Compiles a query and returns a function that can be invoked to execute the query. * * Compiled queries are useful when you need to execute the same query multiple times with different * parameters, or when you want to cache the query for reuse. Compiled query execution is faster than * non-compiled query execution because the query is only compiled once. * * @param query The query function to compile. * @return The compiled query function that can be invoked with the specified arguments. * * @example * const query = db.compile( * (from, $id: number) => from.albums.where(a => a.albumId === $id).single()); * * const album = query(42); */ compile(query: (from: From, ...args: A) => R): (...args: A) => QueryResult; /** * Compiles a query and returns a function that can be invoked to execute the query within a unit of work. * Entity changes made within the unit of work will be tracked and persisted to the database when the * unit of work is committed. * * Compiled queries are useful when you need to execute the same query multiple times with different * parameters, or when you want to cache the query for reuse. Compiled query execution is faster than * non-compiled query execution because the query is only compiled once. * * @param query The query function to compile. * @return The compiled query function that can be invoked with the specified arguments. * * @example * const query = db.compileUow( * (from, $id: number) => from.albums.where(a => a.albumId === $id).single()); * * const uow = db.uow(); * const album = query(uow, 42); */ compileUow(query: (from: From, ...args: A) => R): (uow: UnitOfWork, ...args: A) => QueryResult; /** * Creates a new unit of work, an object that tracks changes to entities and * can be used to persist them to the database. * * @returns A new unit of work. * * @example * const uow = db.uow(); * const customer = * await uow.customers * .where(c => c.name === "Customer 1") * .single(); * * customer.name = "Customer 1 Updated!"; * * await uow.commit(); */ uow(): UnitOfWork; } /** * Creates a new top-level Verse instance, which is the API entry point for data access operations. * * Initialize the Verse instance with {@link Config} and {@link ModelBuilder} objects. * * Query and update operations are accessed through the {@link Verse.from} property and {@link Verse.uow} * function, respectively. * * @param setup The config and model initialization for this Verse instance. * @param setup.config The config object. * @param setup.model The model initialization object. * @return The new instance of Verse. * * @includeExample ../../apps/snippets/src/basic.ts */ export declare function verse(setup: { config: Config; model: ModelBuilder; }): Verse; /** * Contains methods to perform various operations on the current database. */ export declare class DbOperations { #private; /** * Creates a new instance. * * @param metadata The Verse metadata object. */ constructor(metadata: Metadata); /** * Determine whether the target database exists. * @returns A promise that resolves to `true` if the database exists, otherwise `false`. */ exists(): Promise; /** * Get a list of SQL operations that could be executed to create the database schema. * @returns A list of SQL operations. */ schema(): List; /** * Re-create the database schema, and, optionally, seed the database with any seed data defined in the model. * * NB: This will drop the target database if it exists. * * @param seed Whether to seed the database with any seed data defined in the model. * @returns A promise that resolves when the schema has been created. */ recreate(seed?: boolean): Promise; }