UNPKG

@loopback/repository

Version:

Define and implement a common set of interfaces for interacting with databases

378 lines (377 loc) • 18.5 kB
import { Application, Binding, BindingFromClassOptions, BindingScope, Component, Constructor, MixinTarget } from '@loopback/core'; import { Class } from '../common-types'; import { SchemaMigrationOptions } from '../datasource'; import { Model } from '../model'; import { juggler, Repository } from '../repositories'; /** * A mixin class for Application that creates a .repository() * function to register a repository automatically. Also overrides * component function to allow it to register repositories automatically. * * @example * ```ts * class MyApplication extends RepositoryMixin(Application) {} * ``` * * Please note: the members in the mixin function are documented in a dummy class * called <a href="#RepositoryMixinDoc">RepositoryMixinDoc</a> * * @param superClass - Application class * @returns A new class that extends the super class with repository related * methods * * @typeParam T - Type of the application class as the target for the mixin * */ export declare function RepositoryMixin<T extends MixinTarget<Application>>(superClass: T): { new (...args: any[]): { /** * Add a repository to this application. * * @param repoClass - The repository to add. * @param nameOrOptions - Name or options for the binding * * @example * ```ts * * class NoteRepo { * model: any; * * constructor() { * const ds: juggler.DataSource = new juggler.DataSource({ * name: 'db', * connector: 'memory', * }); * * this.model = ds.createModel( * 'note', * {title: 'string', content: 'string'}, * {} * ); * } * }; * * app.repository(NoteRepo); * ``` */ repository<R extends Repository<any>>(repoClass: Class<R>, nameOrOptions?: string | BindingFromClassOptions): Binding<R>; /** * Retrieve the repository instance from the given Repository class * * @param repo - The repository class to retrieve the instance of */ getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R>; /** * Add the dataSource to this application. * * @param dataSource - The dataSource to add. * @param nameOrOptions - The binding name or options of the datasource; * defaults to dataSource.name * * @example * ```ts * * const ds: juggler.DataSource = new juggler.DataSource({ * name: 'db', * connector: 'memory', * }); * * app.dataSource(ds); * * // The datasource can be injected with * constructor(@inject('datasources.db') dataSource: DataSourceType) { * * } * ``` */ dataSource<D extends juggler.DataSource>(dataSource: Class<D> | D, nameOrOptions?: string | BindingFromClassOptions): Binding<D>; /** * Register a model class as a binding in the target context * @param modelClass - Model class */ model<M extends Class<unknown>>(modelClass: M): Binding<M>; /** * Add a component to this application. Also mounts * all the components repositories. * * @param component - The component to add. * @param nameOrOptions - Name or options for the binding. * * @example * ```ts * * export class ProductComponent { * controllers = [ProductController]; * repositories = [ProductRepo, UserRepo]; * providers = { * [AUTHENTICATION_STRATEGY]: AuthStrategy, * [AUTHORIZATION_ROLE]: Role, * }; * }; * * app.component(ProductComponent); * ``` */ component<C extends Component = Component>(componentCtor: Constructor<C>, nameOrOptions?: string | BindingFromClassOptions): Binding<C>; /** * Get an instance of a component and mount all it's * repositories. This function is intended to be used internally * by `component()`. * * NOTE: Calling `mountComponentRepositories` with a component class * constructor is deprecated. You should instantiate the component * yourself and provide the component instance instead. * * @param componentInstanceOrClass - The component to mount repositories of * @internal */ mountComponentRepositories(componentInstanceOrClass: Class<unknown> | RepositoryComponent): void; /** * Bind all model classes provided by a component. * @param component * @internal */ mountComponentModels(component: RepositoryComponent): void; /** * Update or recreate the database schema for all repositories. * * **WARNING**: By default, `migrateSchema()` will attempt to preserve data * while updating the schema in your target database, but this is not * guaranteed to be safe. * * Please check the documentation for your specific connector(s) for * a detailed breakdown of behaviors for automigrate! * * @param options - Migration options, e.g. whether to update tables * preserving data or rebuild everything from scratch. */ migrateSchema(options?: SchemaMigrationOptions): Promise<void>; readonly name: string; readonly subscriptionManager: import("@loopback/context").ContextSubscriptionManager; scope: BindingScope; readonly parent: import("@loopback/context").Context | undefined; emitEvent: <T_1 extends import("@loopback/context").ContextEvent>(type: string, event: T_1) => void; emitError: (err: unknown) => void; bind: <ValueType = any>(key: import("@loopback/context").BindingAddress<ValueType>) => Binding<ValueType>; add: (binding: Binding<unknown>) => Application; configure: <ConfigValueType = any>(key?: import("@loopback/context").BindingAddress) => Binding<ConfigValueType>; getConfigAsValueOrPromise: <ConfigValueType>(key: import("@loopback/context").BindingAddress, propertyPath?: string, resolutionOptions?: import("@loopback/context").ResolutionOptions) => import("@loopback/context").ValueOrPromise<ConfigValueType | undefined>; getConfig: <ConfigValueType>(key: import("@loopback/context").BindingAddress, propertyPath?: string, resolutionOptions?: import("@loopback/context").ResolutionOptions) => Promise<ConfigValueType | undefined>; getConfigSync: <ConfigValueType>(key: import("@loopback/context").BindingAddress, propertyPath?: string, resolutionOptions?: import("@loopback/context").ResolutionOptions) => ConfigValueType | undefined; unbind: (key: import("@loopback/context").BindingAddress) => boolean; subscribe: (observer: import("@loopback/context").ContextEventObserver) => import("@loopback/context").Subscription; unsubscribe: (observer: import("@loopback/context").ContextEventObserver) => boolean; close: () => void; isSubscribed: (observer: import("@loopback/context").ContextObserver) => boolean; createView: <T_1 = unknown>(filter: import("@loopback/context").BindingFilter, comparator?: import("@loopback/context").BindingComparator, options?: Omit<import("@loopback/context").ResolutionOptions, 'session'>) => import("@loopback/context").ContextView<T_1>; contains: (key: import("@loopback/context").BindingAddress) => boolean; isBound: (key: import("@loopback/context").BindingAddress) => boolean; getOwnerContext: (keyOrBinding: import("@loopback/context").BindingAddress | Readonly<Binding<unknown>>) => import("@loopback/context").Context | undefined; getScopedContext: (scope: BindingScope.APPLICATION | BindingScope.SERVER | BindingScope.REQUEST) => import("@loopback/context").Context | undefined; getResolutionContext: (binding: Readonly<Binding<unknown>>) => import("@loopback/context").Context | undefined; isVisibleTo: (ctx: import("@loopback/context").Context) => boolean; find: <ValueType = any>(pattern?: string | RegExp | import("@loopback/context").BindingFilter) => Readonly<Binding<ValueType>>[]; findByTag: <ValueType = any>(tagFilter: import("@loopback/context").BindingTag | RegExp) => Readonly<Binding<ValueType>>[]; get: { <ValueType>(keyWithPath: import("@loopback/context").BindingAddress<ValueType>, session?: import("@loopback/context").ResolutionSession): Promise<ValueType>; <ValueType>(keyWithPath: import("@loopback/context").BindingAddress<ValueType>, options: import("@loopback/context").ResolutionOptions): Promise<ValueType | undefined>; }; getSync: { <ValueType>(keyWithPath: import("@loopback/context").BindingAddress<ValueType>, session?: import("@loopback/context").ResolutionSession): ValueType; <ValueType>(keyWithPath: import("@loopback/context").BindingAddress<ValueType>, options?: import("@loopback/context").ResolutionOptions): ValueType | undefined; }; getBinding: { <ValueType = any>(key: import("@loopback/context").BindingAddress<ValueType>): Binding<ValueType>; <ValueType>(key: import("@loopback/context").BindingAddress<ValueType>, options?: { optional?: boolean; }): Binding<ValueType> | undefined; }; findOrCreateBinding: <T_1>(key: import("@loopback/context").BindingAddress<T_1>, policy?: import("@loopback/context").BindingCreationPolicy) => Binding<T_1>; getValueOrPromise: <ValueType>(keyWithPath: import("@loopback/context").BindingAddress<ValueType>, optionsOrSession?: import("@loopback/context").ResolutionOptionsOrSession) => import("@loopback/context").ValueOrPromise<ValueType | undefined>; toJSON: () => import("@loopback/context").JSONObject; inspect: (options?: import("@loopback/context").ContextInspectOptions) => import("@loopback/context").JSONObject; on: { (eventName: 'bind' | 'unbind', listener: import("@loopback/context").ContextEventListener): Application; (event: string | symbol, listener: (...args: any[]) => void): Application; }; once: { (eventName: 'bind' | 'unbind', listener: import("@loopback/context").ContextEventListener): Application; (event: string | symbol, listener: (...args: any[]) => void): Application; }; readonly options: import("@loopback/core").ApplicationConfig; readonly state: string; controller: <T_1>(controllerCtor: import("@loopback/core").ControllerClass<T_1>, nameOrOptions?: string | BindingFromClassOptions) => Binding<T_1>; server: <T_1 extends import("@loopback/core").Server>(ctor: Constructor<T_1>, nameOrOptions?: string | BindingFromClassOptions) => Binding<T_1>; servers: <T_1 extends import("@loopback/core").Server>(ctors: Constructor<T_1>[]) => Binding[]; getServer: <T_1 extends import("@loopback/core").Server>(target: Constructor<T_1> | string) => Promise<T_1>; init: () => Promise<void>; onInit: (fn: () => import("@loopback/context").ValueOrPromise<void>) => Binding<import("@loopback/core").LifeCycleObserver>; start: () => Promise<void>; onStart: (fn: () => import("@loopback/context").ValueOrPromise<void>) => Binding<import("@loopback/core").LifeCycleObserver>; stop: () => Promise<void>; onStop: (fn: () => import("@loopback/context").ValueOrPromise<void>) => Binding<import("@loopback/core").LifeCycleObserver>; setMetadata: (metadata: import("@loopback/core").ApplicationMetadata) => void; lifeCycleObserver: <T_1 extends import("@loopback/core").LifeCycleObserver>(ctor: Constructor<T_1>, nameOrOptions?: string | BindingFromClassOptions) => Binding<T_1>; service: <S>(cls: import("@loopback/core").ServiceOrProviderClass<S>, nameOrOptions?: string | import("@loopback/core").ServiceOptions) => Binding<S>; interceptor: (interceptor: import("@loopback/context").Interceptor | Constructor<import("@loopback/context").Provider<import("@loopback/context").Interceptor>>, nameOrOptions?: string | import("@loopback/context").InterceptorBindingOptions) => Binding<import("@loopback/context").Interceptor>; [EventEmitter.captureRejectionSymbol]?: (<K>(error: Error, event: string | symbol, ...args: any[]) => void) | undefined; addListener: <K>(eventName: string | symbol, listener: (...args: any[]) => void) => Application; removeListener: <K>(eventName: string | symbol, listener: (...args: any[]) => void) => Application; off: <K>(eventName: string | symbol, listener: (...args: any[]) => void) => Application; removeAllListeners: (eventName?: string | symbol | undefined) => Application; setMaxListeners: (n: number) => Application; getMaxListeners: () => number; listeners: <K>(eventName: string | symbol) => Function[]; rawListeners: <K>(eventName: string | symbol) => Function[]; emit: <K>(eventName: string | symbol, ...args: any[]) => boolean; listenerCount: <K>(eventName: string | symbol, listener?: Function | undefined) => number; prependListener: <K>(eventName: string | symbol, listener: (...args: any[]) => void) => Application; prependOnceListener: <K>(eventName: string | symbol, listener: (...args: any[]) => void) => Application; eventNames: () => (string | symbol)[]; }; } & T; /** * This interface describes additional Component properties * allowing components to contribute Repository-related artifacts. */ export interface RepositoryComponent { /** * An optional list of Repository classes to bind for dependency injection * via `app.repository()` API. */ repositories?: Class<Repository<Model>>[]; /** * An optional list of Model classes to bind for dependency injection * via `app.model()` API. */ models?: Class<Model>[]; } /** * Interface for an Application mixed in with RepositoryMixin */ export interface ApplicationWithRepositories extends Application { repository<R extends Repository<any>>(repo: Class<R>, name?: string): Binding<R>; getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R>; dataSource<D extends juggler.DataSource>(dataSource: Class<D> | D, name?: string): Binding<D>; model<M extends Class<unknown>>(modelClass: M): Binding<M>; component(component: Class<unknown>, name?: string): Binding; mountComponentRepositories(component: Class<unknown>): void; migrateSchema(options?: SchemaMigrationOptions): Promise<void>; } /** * A dummy class created to generate the tsdoc for the members in repository * mixin. Please don't use it. * * The members are implemented in function * <a href="#RepositoryMixin">RepositoryMixin</a> */ export declare class RepositoryMixinDoc { constructor(...args: any[]); /** * Add a repository to this application. * * @param repo - The repository to add. * * @example * ```ts * * class NoteRepo { * model: any; * * constructor() { * const ds: juggler.DataSource = new juggler.DataSource({ * name: 'db', * connector: 'memory', * }); * * this.model = ds.createModel( * 'note', * {title: 'string', content: 'string'}, * {} * ); * } * }; * * app.repository(NoteRepo); * ``` */ repository(repo: Class<Repository<any>>): Binding; /** * Retrieve the repository instance from the given Repository class * * @param repo - The repository class to retrieve the instance of */ getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R>; /** * Add the dataSource to this application. * * @param dataSource - The dataSource to add. * @param name - The binding name of the datasource; defaults to dataSource.name * * @example * ```ts * * const ds: juggler.DataSource = new juggler.DataSource({ * name: 'db', * connector: 'memory', * }); * * app.dataSource(ds); * * // The datasource can be injected with * constructor(@inject('datasources.db') dataSource: DataSourceType) { * * } * ``` */ dataSource(dataSource: Class<juggler.DataSource> | juggler.DataSource, name?: string): Binding; /** * Add a component to this application. Also mounts * all the components repositories. * * @param component - The component to add. * * @example * ```ts * * export class ProductComponent { * controllers = [ProductController]; * repositories = [ProductRepo, UserRepo]; * providers = { * [AUTHENTICATION_STRATEGY]: AuthStrategy, * [AUTHORIZATION_ROLE]: Role, * }; * }; * * app.component(ProductComponent); * ``` */ component(component: Class<{}>): Binding; /** * Get an instance of a component and mount all it's * repositories. This function is intended to be used internally * by component() * * @param component - The component to mount repositories of */ mountComponentRepository(component: Class<{}>): void; /** * Update or recreate the database schema for all repositories. * * **WARNING**: By default, `migrateSchema()` will attempt to preserve data * while updating the schema in your target database, but this is not * guaranteed to be safe. * * Please check the documentation for your specific connector(s) for * a detailed breakdown of behaviors for automigrate! * * @param options - Migration options, e.g. whether to update tables * preserving data or rebuild everything from scratch. */ migrateSchema(options?: SchemaMigrationOptions): Promise<void>; } /** * Create a binding for the given model class * @param modelClass - Model class */ export declare function createModelClassBinding<M extends Class<unknown>>(modelClass: M): Binding<M>;