@loopback/repository
- Version 7.0.10
- Published
- 820 kB
- 6 dependencies
- MIT license
Install
npm i @loopback/repository
yarn add @loopback/repository
pnpm add @loopback/repository
Overview
A common set of interfaces for interacting with databases.
This module provides data access facilities to various databases and services as well as the constructs for modeling and accessing those data.
Index
Variables
Functions
- belongsTo()
- bindModel()
- buildLookupMap()
- buildModelDefinition()
- constrainDataObject()
- constrainDataObjects()
- constrainFilter()
- constrainWhere()
- constrainWhereOr()
- createBelongsToAccessor()
- createBelongsToInclusionResolver()
- createHasManyInclusionResolver()
- createHasManyRepositoryFactory()
- createHasManyThroughRepositoryFactory()
- createHasOneRepositoryFactory()
- createModelClassBinding()
- createReferencesManyAccessor()
- createReferencesManyInclusionResolver()
- deduplicate()
- defineCrudRepositoryClass()
- defineKeyValueRepositoryClass()
- defineModelClass()
- defineRepositoryClass()
- embedsMany()
- embedsOne()
- ensurePromise()
- findByForeignKeys()
- flattenMapByKeys()
- flattenTargetsOfOneToManyRelation()
- flattenTargetsOfOneToOneRelation()
- getKeyValue()
- getModelRelations()
- hasMany()
- hasOne()
- includeFieldIfNot()
- includeRelatedModels()
- isBsonType()
- isBuiltinType()
- isEntityNotFoundError()
- isInvalidBodyError()
- isInvalidPolymorphismError()
- isInvalidRelationError()
- isTypeResolver()
- model()
- normalizeKey()
- Null()
- property()
- reduceAsArray()
- reduceAsSingleItem()
- referencesMany()
- referencesOne()
- rejectNavigationalPropertiesInData()
- relation()
- repository()
- RepositoryMixin()
- resolveType()
Classes
DefaultCrudRepository
- count()
- create()
- createAll()
- createBelongsToAccessorFor()
- createHasManyRepositoryFactoryFor()
- createHasManyThroughRepositoryFactoryFor()
- createHasOneRepositoryFactoryFor()
- createReferencesManyAccessorFor()
- dataSource
- definePersistedModel()
- delete()
- deleteAll()
- deleteById()
- ensurePersistable()
- entityClass
- entityToData()
- execute()
- exists()
- find()
- findById()
- findOne()
- includeRelatedModels()
- inclusionResolvers
- modelClass
- normalizeFilter()
- registerInclusionResolver()
- replaceById()
- save()
- toEntities()
- toEntity()
- update()
- updateAll()
- updateById()
Interfaces
Enums
Type Aliases
- Callback
- Command
- Constructor
- DataObject
- DeepPartial
- DynamicModelCtor
- EntityData
- EntityResolver
- HasManyThroughRepositoryFactory
- InclusionResolver
- KeyValueFilter
- NamedParameters
- NonFunction
- Options
- PositionalParameters
- PropertyMap
- PropertyType
- PrototypeOf
- RelationDefinitionMap
- RelationMetadata
- RepositoryDecorator
- StringKeyOf
- TransactionalEntityRepository
- TypeResolver
Namespaces
Variables
variable ANY
const ANY: AnyType;
variable BOOLEAN
const BOOLEAN: BooleanType;
variable BUFFER
const BUFFER: BufferType;
variable CountSchema
const CountSchema: { type: 'object'; title: string; 'x-typescript-type': string; properties: { count: { type: 'number' } };};
JSON Schema describing the Count interface. It's the response type for REST calls to APIs which return
count
. The type is compatible withSchemaObject
from@loopback/openapi-v3
, which is not an explicit dependency for@loopback/repository
.
variable DATE
const DATE: DateType;
variable MODEL_KEY
const MODEL_KEY: MetadataAccessor<Partial<ModelDefinitionSyntax>, ClassDecorator>;
variable MODEL_PROPERTIES_KEY
const MODEL_PROPERTIES_KEY: MetadataAccessor<PropertyDefinition, PropertyDecorator>;
variable MODEL_WITH_PROPERTIES_KEY
const MODEL_WITH_PROPERTIES_KEY: MetadataAccessor<ModelDefinition, ClassDecorator>;
variable NULL
const NULL: NullType;
variable NUMBER
const NUMBER: NumberType;
variable RELATIONS_KEY
const RELATIONS_KEY: string;
variable STRING
const STRING: StringType;
Functions
function belongsTo
belongsTo: <T extends Entity>( targetResolver: EntityResolver<T>, definition?: Partial<BelongsToDefinition>, propertyDefinition?: Partial<PropertyDefinition>) => (decoratedTarget: Entity, decoratedKey: string) => void;
Decorator for belongsTo
Parameter targetResolver
A resolver function that returns the target model for a belongsTo relation
Parameter definition
Optional metadata for setting up a belongsTo relation
Parameter propertyDefinition
Optional metadata for setting up the property
Returns
A property decorator
function bindModel
bindModel: <T extends juggler.ModelBaseClass>( modelClass: T, ds: juggler.DataSource) => T;
This is a bridge to the legacy DAO class. The function mixes DAO methods into a model class and attach it to a given data source
Parameter modelClass
Model class
Parameter ds
Data source
Returns
{} The new model class with DAO (CRUD) operations
function buildLookupMap
buildLookupMap: <Key, InType extends object, OutType = InType>( list: InType[], keyName: StringKeyOf<InType>, reducer: (accumulator: OutType | undefined, current: InType) => OutType) => Map<Key, OutType>;
Returns a map which maps key values(ids) to instances. The instances can be grouped by different strategies.
Parameter list
an array of instances
Parameter keyName
key name of the source
Parameter reducer
a strategy to reduce inputs to single item or array
function buildModelDefinition
buildModelDefinition: ( target: Function & { definition?: ModelDefinition | undefined }, def?: ModelDefinitionSyntax) => ModelDefinition;
Build model definition from decorations
Parameter target
Target model class
Parameter def
Model definition spec
function constrainDataObject
constrainDataObject: <T extends Entity>( originalData: DataObject<T>, constraint: DataObject<T>) => DataObject<T>;
A utility function which takes a model instance data and enforces constraint(s) on it
Parameter originalData
the model data to apply the constrain(s) to
Parameter constraint
the constraint which is to be applied on the data object
Returns
the modified data with the constraint, otherwise the original instance data
function constrainDataObjects
constrainDataObjects: <T extends Entity>( originalData: DataObject<T>[], constraint: DataObject<T>) => DataObject<T>[];
A utility function which takes an array of model instance data and enforces constraint(s) on it
Parameter originalData
the array of model data to apply the constrain(s) to
Parameter constraint
the constraint which is to be applied on the data objects
Returns
an array of the modified data with the constraint, otherwise the original instance data array
function constrainFilter
constrainFilter: <T extends object>( originalFilter: Filter<T> | undefined, constraint: AnyObject) => Filter<T>;
A utility function which takes a filter and enforces constraint(s) on it
Parameter originalFilter
the filter to apply the constrain(s) to
Parameter constraint
the constraint which is to be applied on the filter
Returns
Filter the modified filter with the constraint, otherwise the original filter
function constrainWhere
constrainWhere: <T extends object>( originalWhere: Where<T> | undefined, constraint: Where<T>) => Where<T>;
A utility function which takes a where filter and enforces constraint(s) on it
Parameter originalWhere
the where filter to apply the constrain(s) to
Parameter constraint
the constraint which is to be applied on the filter
Returns
Filter the modified filter with the constraint, otherwise the original filter
function constrainWhereOr
constrainWhereOr: <T extends object>( originalWhere: Where<T> | undefined, constraint: Where<T>[]) => Where<T>;
A utility function which takes a where filter and enforces constraint(s) on it with OR clause
Parameter originalWhere
the where filter to apply the constrain(s) to
Parameter constraint
the constraint which is to be applied on the filter with or clause
Returns
Filter the modified filter with the constraint, otherwise the original filter
function createBelongsToAccessor
createBelongsToAccessor: < Target extends Entity, TargetId, Source extends Entity, SourceId>( belongsToMetadata: BelongsToDefinition, targetRepositoryGetter: any, sourceRepository: EntityCrudRepository<Source, SourceId>) => BelongsToAccessor<Target, SourceId>;
Enforces a BelongsTo constraint on a repository If the target model is polymorphic, i.e. stored within different repositories, supply the targetRepositoryGetter with a dictionary in the form of {[typeName: string]: repositoryGetter}
function createBelongsToInclusionResolver
createBelongsToInclusionResolver: < Target extends Entity, TargetID, TargetRelations extends object>( meta: BelongsToDefinition, getTargetRepoDict: { [repoType: string]: Getter< EntityCrudRepository<Target, TargetID, TargetRelations> >; }) => InclusionResolver<Entity, Target>;
Creates InclusionResolver for BelongsTo relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.
Notice: scope field for inclusion is not supported yet
Parameter meta
resolved BelongsToMetadata
Parameter getTargetRepoDict
dictionary of target model type - target repository i.e where related instances for different types are
function createHasManyInclusionResolver
createHasManyInclusionResolver: < Target extends Entity, TargetID, TargetRelations extends object>( meta: HasManyDefinition, getTargetRepo: Getter<EntityCrudRepository<Target, TargetID, TargetRelations>>) => InclusionResolver<Entity, Target>;
Creates InclusionResolver for HasMany relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.
Notice: scope field for inclusion is not supported yet.
Parameter meta
resolved metadata of the hasMany relation
Parameter getTargetRepo
target repository i.e where related instances are
function createHasManyRepositoryFactory
createHasManyRepositoryFactory: < Target extends Entity, TargetID, ForeignKeyType>( relationMetadata: HasManyDefinition, targetRepositoryGetter: Getter<EntityCrudRepository<Target, TargetID, {}>>) => HasManyRepositoryFactory<Target, ForeignKeyType>;
Enforces a constraint on a repository based on a relationship contract between models. For example, if a Customer model is related to an Order model via a HasMany relation, then, the relational repository returned by the factory function would be constrained by a Customer model instance's id(s).
Parameter relationMetadata
The relation metadata used to describe the relationship and determine how to apply the constraint.
Parameter targetRepositoryGetter
The repository which represents the target model of a relation attached to a datasource.
Returns
The factory function which accepts a foreign key value to constrain the given target repository
function createHasManyThroughRepositoryFactory
createHasManyThroughRepositoryFactory: < Target extends Entity, TargetID, Through extends Entity, ThroughID, SourceID>( relationMetadata: HasManyDefinition, targetRepositoryGetter: any, throughRepositoryGetter: Getter<EntityCrudRepository<Through, ThroughID, {}>>) => HasManyThroughRepositoryFactory<Target, TargetID, Through, SourceID>;
function createHasOneRepositoryFactory
createHasOneRepositoryFactory: <Target extends Entity, TargetID, ForeignKeyType>( relationMetadata: HasOneDefinition, targetRepositoryGetter: any) => HasOneRepositoryFactory<Target, ForeignKeyType>;
Enforces a constraint on a repository based on a relationship contract between models. For example, if a Customer model is related to an Address model via a HasOne relation, then, the relational repository returned by the factory function would be constrained by a Customer model instance's id(s).
If the target model is polymorphic, i.e. stored within different repositories, supply the targetRepositoryGetter with a dictionary in the form of {[typeName: string]: repositoryGetter}
Parameter relationMetadata
The relation metadata used to describe the relationship and determine how to apply the constraint.
Parameter targetRepositoryGetter
The repository or a dictionary of classname - repository, which represents the target model of a relation attached to a datasource. For the dictionary, the key is the class name of the concrete class the the polymorphic model.
Returns
The factory function which accepts a foreign key value to constrain the given target repository
function createModelClassBinding
createModelClassBinding: <M extends Class<unknown>>(modelClass: M) => Binding<M>;
Create a binding for the given model class
Parameter modelClass
Model class
function createReferencesManyAccessor
createReferencesManyAccessor: < Target extends Entity, TargetIds, Source extends Entity, SourceId>( referencesManyMetadata: ReferencesManyDefinition, targetRepoGetter: Getter<EntityCrudRepository<Target, TargetIds, {}>>, sourceRepository: EntityCrudRepository<Source, SourceId>) => ReferencesManyAccessor<Target, SourceId>;
Enforces a ReferencesMany constraint on a repository
function createReferencesManyInclusionResolver
createReferencesManyInclusionResolver: < Target extends Entity, TargetIds, TargetRelations extends object>( meta: ReferencesManyDefinition, getTargetRepo: Getter<EntityCrudRepository<Target, TargetIds, TargetRelations>>) => InclusionResolver<Entity, Target>;
Creates InclusionResolver for ReferencesMany relation. Notice that this function only generates the inclusionResolver. It doesn't register it for the source repository.
Notice: scope field for inclusion is not supported yet
Parameter meta
resolved ReferencesManyMetadata
Parameter getTargetRepo
target repository i.e where related instances are
function deduplicate
deduplicate: <T>(input: T[]) => T[];
Dedupe an array
Parameter input
an array of sourceIds
Returns
an array with unique items
function defineCrudRepositoryClass
defineCrudRepositoryClass: <E extends Entity, IdType, Relations extends object>( entityClass: typeof Entity & { prototype: E }) => ModelRepositoryClass<E, DefaultCrudRepository<E, IdType, Relations>>;
Create (define) an entity CRUD repository class for the given model. This function always uses
DefaultCrudRepository
as the base class, usedefineRepositoryClass
if you want to use your own base repository.Parameter entityClass
An entity class such as
Product
.Example 1
const ProductRepository = defineCrudRepositoryClass<Product,typeof Product.prototype.id,ProductRelations>(Product);
function defineKeyValueRepositoryClass
defineKeyValueRepositoryClass: <M extends Model>( modelClass: typeof Model & { prototype: M }) => ModelRepositoryClass<M, DefaultKeyValueRepository<M>>;
Create (define) a KeyValue repository class for the given entity. This function always uses
DefaultKeyValueRepository
as the base class, usedefineRepositoryClass
if you want to use your own base repository.Parameter modelClass
An entity class such as
Product
.Example 1
const ProductKeyValueRepository = defineKeyValueRepositoryClass(Product);
function defineModelClass
defineModelClass: <BaseCtor extends typeof Model, Props extends object = {}>( base: BaseCtor, definition: ModelDefinition) => DynamicModelCtor<BaseCtor, Props>;
Create (define) a new model class with the given name and definition.
Parameter base
The base model to extend, typically Model or Entity. You can also use your own base class, e.g.
User
.Parameter definition
Definition of the model to create.
Remarks
const Product = defineModelClass(Entity, new ModelDefinition('Product'));To enable type safety, you should describe properties of your model:
const Product = defineModelClass<typeof Entity,{id: number, name: string}>(Entity, new ModelDefinition('Product'));If your model allows arbitrary (free-form) properties, then add
AnyObject
to the type describing model properties.const Product = defineModelClass<typeof Entity,AnyObject & {id: number},>(Entity, new ModelDefinition('Product'));
function defineRepositoryClass
defineRepositoryClass: < M extends typeof Model, R extends Repository<PrototypeOf<M>>>( modelClass: M, baseRepositoryClass: BaseRepositoryClass<M, R>) => ModelRepositoryClass<PrototypeOf<M>, R>;
Create (define) a repository class for the given model.
See also
defineCrudRepositoryClass
anddefineKeyValueRepositoryClass
for convenience wrappers providing repository class factory for the default CRUD and KeyValue implementations.**❗️IMPORTANT: The compiler (TypeScript 3.8) is not able to correctly infer generic arguments
M
andR
from the class constructors provided in function arguments. You must always provide both M and R types explicitly.**Parameter modelClass
A model class such as
Address
.Parameter baseRepositoryClass
Repository implementation to use as the base, e.g.
DefaultCrudRepository
.Example 1
const AddressRepository = defineRepositoryClass<typeof Address,DefaultEntityCrudRepository<Address,typeof Address.prototype.id,AddressRelations>,>(Address, DefaultCrudRepository);
function embedsMany
embedsMany: (definition?: Object) => PropertyDecorator;
Decorator for embedsMany
Parameter definition
Returns
A property decorator
function embedsOne
embedsOne: (definition?: Object) => PropertyDecorator;
Decorator for embedsOne
Parameter definition
Returns
A property decorator
function ensurePromise
ensurePromise: <T>(p: legacy.PromiseOrVoid<T>) => Promise<T>;
Ensure the value is a promise
Parameter p
Promise or void
function findByForeignKeys
findByForeignKeys: < Target extends Entity, TargetRelations extends object, ForeignKey extends Extract<keyof Target, string>>( targetRepository: EntityCrudRepository<Target, unknown, TargetRelations>, fkName: ForeignKey, fkValues: Target[ForeignKey][] | Target[ForeignKey], scope?: Filter<Target> & { totalLimit?: number }, options?: Options) => Promise<(Target & TargetRelations)[]>;
Finds model instances that contain any of the provided foreign key values.
Parameter targetRepository
The target repository where the related model instances are found
Parameter fkName
Name of the foreign key
Parameter fkValues
One value or array of values of the foreign key to be included
Parameter scope
Additional scope constraints
Parameter options
Options for the operations
function flattenMapByKeys
flattenMapByKeys: <T>( sourceIds: unknown[], targetMap: Map<unknown, T>) => (T | undefined)[];
Returns an array of instances from the target map. The order of arrays is based on the order of sourceIds
Parameter sourceIds
One value or array of values (of the target key)
Parameter targetMap
a map that matches sourceIds with instances
function flattenTargetsOfOneToManyRelation
flattenTargetsOfOneToManyRelation: <Target extends Entity>( sourceIds: unknown[], targetEntities: Target[], targetKey: StringKeyOf<Target>) => (Target[] | undefined)[];
Returns an array of instances. The order of arrays is based on as a result of one to many relation. The order of arrays is based on the order of sourceIds
Parameter sourceIds
One value or array of values of the target key
Parameter targetEntities
target entities that satisfy targetKey's value (ids).
Parameter targetKey
name of the target key
function flattenTargetsOfOneToOneRelation
flattenTargetsOfOneToOneRelation: <Target extends Entity>( sourceIds: unknown[], targetEntities: Target[], targetKey: StringKeyOf<Target>) => (Target | undefined)[];
Returns an array of instances. The order of arrays is based on the order of sourceIds
Parameter sourceIds
One value or array of values of the target key
Parameter targetEntities
target entities that satisfy targetKey's value (ids).
Parameter targetKey
name of the target key
function getKeyValue
getKeyValue: (model: AnyObject, keyName: string) => unknown;
Returns value of a keyName. Aims to resolve ObjectId problem of Mongo.
Parameter model
target model
Parameter keyName
target key that gets the value from
function getModelRelations
getModelRelations: (modelCtor: typeof Model) => RelationDefinitionMap;
Get metadata of all relations defined on a given model class.
Parameter modelCtor
The model class (the constructor function).
Returns
A map of relation definitions
function hasMany
hasMany: <T extends Entity>( targetResolver: EntityResolver<T>, definition?: Partial<HasManyDefinition>) => (decoratedTarget: object, key: string) => void;
Decorator for hasMany Calls property.array decorator underneath the hood and infers foreign key name from target model name unless explicitly specified
Parameter targetResolver
Target model for hasMany relation
Parameter definition
Optional metadata for setting up hasMany relation
Returns
A property decorator
function hasOne
hasOne: <T extends Entity>( targetResolver: EntityResolver<T>, definition?: Partial<HasOneDefinition>) => (decoratedTarget: object, key: string) => void;
function includeFieldIfNot
includeFieldIfNot: <MT>( fields: Fields<MT> | undefined, fieldToInclude: Extract<keyof MT, string>) => false | Fields<MT>;
function includeRelatedModels
includeRelatedModels: <T extends Entity, Relations extends object = {}>( targetRepository: EntityCrudRepository<T, unknown, Relations>, entities: T[], include?: InclusionFilter[], options?: Options) => Promise<(T & Relations)[]>;
Returns model instances that include related models that have a registered resolver.
Parameter targetRepository
The target repository where the model instances are found
Parameter entities
An array of entity instances or data
Parameter include
Inclusion filter
Parameter options
Options for the operations
function isBsonType
isBsonType: (value: unknown) => value is object;
Checks if the value is BsonType (mongodb) It uses a general way to check the type ,so that it can detect different versions of bson that might be used in the code base. Might need to update in the future.
Parameter value
function isBuiltinType
isBuiltinType: (fn: Function) => boolean;
Check if the provided function is a built-in type provided by JavaScript and/or Node.js. E.g.
Number
,Array
,Buffer
, etc.
function isEntityNotFoundError
isEntityNotFoundError: (e: any) => e is EntityNotFoundError<any, {}>;
function isInvalidBodyError
isInvalidBodyError: (e: any) => e is InvalidBodyError<any, {}>;
function isInvalidPolymorphismError
isInvalidPolymorphismError: (e: any) => e is InvalidPolymorphismError<any>;
function isInvalidRelationError
isInvalidRelationError: (e: any) => e is InvalidRelationError<any>;
function isTypeResolver
isTypeResolver: <T extends object>(fn: any) => fn is TypeResolver<T, Function>;
A function that checks whether a function is a TypeResolver or not.
Parameter fn
The value to check.
function model
model: ( definition?: Partial<ModelDefinitionSyntax>) => (target: Function & { definition?: ModelDefinition }) => void;
Decorator for model definitions
Parameter definition
Returns
A class decorator for
model
function normalizeKey
normalizeKey: (rawKey: unknown) => unknown;
Workaround for MongoDB, where the connector returns ObjectID values even for properties configured with "type: string".
Parameter rawKey
function Null
Null: () => null;
A boxed type for
null
function property
property: typeof property;
Decorator for model properties
Parameter definition
Returns
A property decorator
function reduceAsArray
reduceAsArray: <T>(acc: T[] | undefined, it: T) => T[];
Returns an array of instances. For HasMany relation usage.
Parameter acc
Parameter it
function reduceAsSingleItem
reduceAsSingleItem: <T>(_acc: T | undefined, it: T) => T;
Returns a single of an instance. For HasOne and BelongsTo relation usage.
Parameter _acc
Parameter it
function referencesMany
referencesMany: <T extends Entity>( targetResolver: EntityResolver<T>, definition?: Partial<ReferencesManyDefinition>, propertyDefinition?: Partial<PropertyDefinition>) => (decoratedTarget: Entity, decoratedKey: string) => void;
Decorator for referencesMany
Parameter targetResolver
A resolver function that returns the target model for a referencesMany relation
Parameter definition
Optional metadata for setting up a referencesMany relation
Parameter propertyDefinition
Optional metadata for setting up the property
Returns
A property decorator
function referencesOne
referencesOne: (definition?: Object) => PropertyDecorator;
Decorator for referencesOne
Parameter definition
Returns
A property decorator
function rejectNavigationalPropertiesInData
rejectNavigationalPropertiesInData: <M extends typeof Entity>( modelClass: M, data: DataObject<PrototypeOf<M>>) => void;
Check model data for navigational properties linking to related models. Throw a descriptive error if any such property is found.
Parameter modelClass
Model constructor, e.g.
Product
.Parameter entityData
Model instance or a plain-data object, e.g.
{name: 'pen'}
.
function relation
relation: (definition?: Object) => PropertyDecorator;
Decorator for relations
Parameter definition
Returns
A property decorator
function repository
repository: typeof repository;
Decorator for repository injections on properties or method arguments
Parameter repositoryName
Name of the repo
Example 1
class CustomerController {@repository(CustomerRepository) public custRepo: CustomerRepository;constructor(@repository(ProductRepository) public prodRepo: ProductRepository,) {}// ...}Decorator for DefaultCrudRepository generation and injection on properties or method arguments based on the given model and dataSource (or their names)
Parameter model
Name/class of the model
Parameter dataSource
Name/instance of the dataSource
Example 1
class CustomerController {@repository('Customer', 'mySqlDataSource')public custRepo: DefaultCrudRepository<Customer,typeof Customer.prototype.id>;constructor(@repository(Product, mySqlDataSource)public prodRepo: DefaultCrudRepository<Product,typeof Product.prototype.id>,) {}// ...}
function RepositoryMixin
RepositoryMixin: <T extends MixinTarget<Application>>( superClass: T) => (new (...args: any[]) => { repository<R extends Repository<any>>( repoClass: Class<R>, nameOrOptions?: string | BindingFromClassOptions ): Binding<R>; getRepository<R_1 extends Repository<any>>(repo: Class<R_1>): Promise<R_1>; dataSource<D extends juggler.DataSource>( dataSource: D | Class<D>, nameOrOptions?: string | BindingFromClassOptions ): Binding<D>; model<M extends Class<unknown>>(modelClass: M): Binding<M>; component<C extends Component = Component>( componentCtor: Constructor<C>, nameOrOptions?: string | BindingFromClassOptions ): Binding<C>; mountComponentRepositories( componentInstanceOrClass: Class<unknown> | RepositoryComponent ): void; mountComponentModels(component: RepositoryComponent): void; migrateSchema(options?: SchemaMigrationOptions): Promise<void>; readonly options: any; readonly state: string; controller: <T>( controllerCtor: any, nameOrOptions?: string | BindingFromClassOptions | undefined ) => Binding<T>; server: <T_1 extends any>( ctor: Constructor<T_1>, nameOrOptions?: string | BindingFromClassOptions | undefined ) => Binding<T_1>; servers: <T_2 extends any>(ctors: Constructor<T_2>[]) => Binding<any>[]; getServer: <T_3 extends any>(target: any) => Promise<T_3>; init: () => Promise<void>; onInit: ( fn: () => import('@loopback/core').ValueOrPromise<void> ) => Binding<any>; start: () => Promise<void>; onStart: ( fn: () => import('@loopback/core').ValueOrPromise<void> ) => Binding<any>; stop: () => Promise<void>; onStop: ( fn: () => import('@loopback/core').ValueOrPromise<void> ) => Binding<any>; setMetadata: (metadata: any) => void; lifeCycleObserver: <T_4 extends any>( ctor: Constructor<T_4>, nameOrOptions?: string | BindingFromClassOptions | undefined ) => Binding<T_4>; service: <S>( cls: any, nameOrOptions?: string | import('@loopback/core').ServiceOptions | undefined ) => Binding<S>; interceptor: ( interceptor: | import('@loopback/core').Interceptor | Constructor< import('@loopback/core').Provider< import('@loopback/core').Interceptor > >, nameOrOptions?: | string | import('@loopback/core').InterceptorBindingOptions | undefined ) => Binding<any>; readonly name: string; readonly subscriptionManager: any; scope: BindingScope; readonly parent: import('@loopback/core').Context | undefined; emitEvent: <T_5 extends any>(type: string, event: T_5) => void; emitError: (err: unknown) => void; bind: <ValueType = any>(key: any) => Binding<ValueType>; add: (binding: Binding<unknown>) => Application; configure: <ConfigValueType = any>( key?: import('@loopback/core').BindingAddress | undefined ) => Binding<ConfigValueType>; getConfigAsValueOrPromise: <ConfigValueType_1>( key: any, propertyPath?: string | undefined, resolutionOptions?: import('@loopback/core').ResolutionOptions | undefined ) => any; getConfig: <ConfigValueType_2>( key: any, propertyPath?: string | undefined, resolutionOptions?: import('@loopback/core').ResolutionOptions | undefined ) => Promise<ConfigValueType_2>; getConfigSync: <ConfigValueType_3>( key: any, propertyPath?: string | undefined, resolutionOptions?: import('@loopback/core').ResolutionOptions | undefined ) => ConfigValueType_3; unbind: (key: any) => boolean; subscribe: (observer: any) => any; unsubscribe: (observer: any) => boolean; close: () => void; isSubscribed: (observer: any) => boolean; createView: <T_6 = unknown>( filter: any, comparator?: import('@loopback/core').BindingComparator | undefined, options?: | Omit<import('@loopback/core').ResolutionOptions, 'session'> | undefined ) => any; contains: (key: any) => boolean; isBound: (key: any) => boolean; getOwnerContext: ( keyOrBinding: | import('@loopback/core').BindingAddress | Readonly<Binding<unknown>> ) => import('@loopback/core').Context | undefined; getScopedContext: ( scope: BindingScope.APPLICATION | BindingScope.SERVER | BindingScope.REQUEST ) => import('@loopback/core').Context | undefined; getResolutionContext: ( binding: Binding<unknown> ) => import('@loopback/core').Context | undefined; isVisibleTo: (ctx: any) => boolean; find: <ValueType_1 = any>( pattern?: | string | RegExp | import('@loopback/core').BindingFilter | undefined ) => Binding<ValueType_1>[]; findByTag: <ValueType_2 = any>( tagFilter: RegExp | import('@loopback/core').BindingTag ) => Binding<ValueType_2>[]; get: { <ValueType_3>( keyWithPath: any, session?: import('@loopback/core').ResolutionSession | undefined ): Promise<ValueType_3>; <ValueType_4>(keyWithPath: any, options: any): Promise<ValueType_4>; }; getSync: { <ValueType_5>( keyWithPath: any, session?: import('@loopback/core').ResolutionSession | undefined ): ValueType_5; <ValueType_6>( keyWithPath: any, options?: import('@loopback/core').ResolutionOptions | undefined ): ValueType_6; }; getBinding: { <ValueType_7 = any>(key: any): Binding<ValueType_7>; <ValueType_8>( key: any, options?: { optional?: boolean | undefined } | undefined ): any; }; findOrCreateBinding: <T_7>( key: any, policy?: import('@loopback/core').BindingCreationPolicy | undefined ) => Binding<T_7>; getValueOrPromise: <ValueType_9>( keyWithPath: any, optionsOrSession?: | import('@loopback/core').ResolutionOptionsOrSession | undefined ) => any; toJSON: () => import('@loopback/core').JSONObject; inspect: ( options?: import('@loopback/core').ContextInspectOptions | undefined ) => any; on: { (eventName: 'bind' | 'unbind', listener: any): Application; (event: string | symbol, listener: (...args: any[]) => void): Application; }; once: { (eventName: 'bind' | 'unbind', listener: any): Application; (event: string | symbol, listener: (...args: any[]) => void): Application; }; addListener: <K_1>( eventName: string | symbol, listener: (...args: any[]) => void ) => Application; removeListener: <K_2>( eventName: string | symbol, listener: (...args: any[]) => void ) => Application; off: <K_3>( eventName: string | symbol, listener: (...args: any[]) => void ) => Application; removeAllListeners: (event?: string | symbol | undefined) => Application; setMaxListeners: (n: number) => Application; getMaxListeners: () => number; listeners: <K_4>(eventName: string | symbol) => Function[]; rawListeners: <K_5>(eventName: string | symbol) => Function[]; emit: <K_6>(eventName: string | symbol, ...args: any[]) => boolean; listenerCount: <K_7>( eventName: string | symbol, listener?: Function | undefined ) => number; prependListener: <K_8>( eventName: string | symbol, listener: (...args: any[]) => void ) => Application; prependOnceListener: <K_9>( eventName: string | symbol, listener: (...args: any[]) => void ) => Application; eventNames: () => (string | symbol)[];}) & T;
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.
Parameter superClass
Application class
Returns
A new class that extends the super class with repository related methods
Example 1
class MyApplication extends RepositoryMixin(Application) {}Please note: the members in the mixin function are documented in a dummy class called RepositoryMixinDoc
function resolveType
resolveType: { <T extends object>(fn: TypeResolver<T, {}> | Class<T> | Function): Class<T>; <T>(fn: NonFunction<T>): T;};
Resolve a type value that may have been provided via TypeResolver.
Parameter fn
A type class or a type provider.
Returns
The resolved type.
Classes
class AnyType
class AnyType implements Type<any> {}
Any type
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => any;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: any) => any;
class ArrayType
class ArrayType<T> implements Type<T[]> {}
Array type, such as string[]
constructor
constructor(itemType: Type<T>);
property itemType
itemType: Type<T>;
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => T[];
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: T[] | null | undefined) => any[] | null | undefined;
class BooleanType
class BooleanType implements Type<boolean> {}
Boolean type
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => boolean;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: boolean | null | undefined) => boolean | null | undefined;
class BufferType
class BufferType implements Type<Buffer> {}
Buffer (binary) type
property name
readonly name: string;
method coerce
coerce: (value: any, options?: Options) => any;
method defaultValue
defaultValue: () => Buffer;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: ( value: Buffer | null | undefined, options?: Options) => string | null | undefined;
class CrudRepositoryImpl
class CrudRepositoryImpl<T extends Entity, ID> implements EntityCrudRepository<T, ID> {}
Repository implementation
Example 1
User can import
CrudRepositoryImpl
and call its functions like:CrudRepositoryImpl.find(somefilters, someoptions)
Or extend class
CrudRepositoryImpl
and override its functions:export class TestRepository extends CrudRepositoryImpl<Test> {constructor(dataSource: DataSource, model: Test) {super(dataSource, Customer);}// Override `deleteAll` to disable the operationdeleteAll(where?: Where, options?: Options) {return Promise.reject(new Error('deleteAll is disabled'));}}
constructor
constructor( dataSource: DataSource, entityClass: typeof Entity & { prototype: T });
property dataSource
dataSource: DataSource;
property entityClass
entityClass: typeof Entity & { prototype: T };
property inclusionResolvers
readonly inclusionResolvers: Map<string, InclusionResolver<T, Entity>>;
method count
count: (where?: Where<T>, options?: Options) => Promise<Count>;
method create
create: (entity: DataObject<T>, options?: Options) => Promise<T>;
method createAll
createAll: (entities: DataObject<T>[], options?: Options) => Promise<T[]>;
method delete
delete: (entity: DataObject<T>, options?: Options) => Promise<void>;
method deleteAll
deleteAll: (where?: Where<T>, options?: Options) => Promise<Count>;
method deleteById
deleteById: (id: ID, options?: Options) => Promise<void>;
method execute
execute: ( command: Command, parameters: NamedParameters | PositionalParameters, options?: Options) => Promise<AnyObject>;
method exists
exists: (id: ID, options?: Options) => Promise<boolean>;
method find
find: (filter?: Filter<T>, options?: Options) => Promise<T[]>;
method findById
findById: ( id: ID, filter?: FilterExcludingWhere<T>, options?: Options) => Promise<T>;
method replaceById
replaceById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
method save
save: (entity: DataObject<T>, options?: Options) => Promise<T>;
method update
update: (entity: DataObject<T>, options?: Options) => Promise<void>;
method updateAll
updateAll: ( data: DataObject<T>, where?: Where<T>, options?: Options) => Promise<Count>;
method updateById
updateById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
class DateType
class DateType implements Type<Date> {}
Date type
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => Date;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: Date | null | undefined) => string | null | undefined;
class DefaultBelongsToRepository
class DefaultBelongsToRepository< TargetEntity extends Entity, TargetId, TargetRepository extends EntityCrudRepository<TargetEntity, TargetId>> implements BelongsToRepository<TargetEntity> {}
constructor
constructor( getTargetRepository: any, constraint: DataObject<TargetEntity>, targetResolver: TypeResolver<Entity, typeof Entity>);
Constructor of DefaultBelongsToEntityCrudRepository
Parameter getTargetRepository
either a dictionary of target model type - target repository instance or a single target repository instance e.g. if the target is of a non-polymorphic type "Student", put the studentRepositoryGetterInstance if the target is of a polymorphic type "Person" which can be either a "Student" or a "Teacher" then put "{Student: studentRepositoryGetterInstance, Teacher: teacherRepositoryGetterInstance}"
Parameter constraint
the key value pair representing foreign key name to constrain the target repository instance
Parameter targetResolver
() => Target to resolve the target class e.g. if the target is of type "Student", then put "() => Student"
property constraint
constraint: DataObject<TargetEntity>;
property getTargetRepository
getTargetRepository: any;
property getTargetRepositoryDict
getTargetRepositoryDict: { [repoType: string]: Getter<TargetRepository> };
property targetResolver
targetResolver: TypeResolver<Entity, typeof Entity>;
method get
get: ( options?: Options & { polymorphicType?: string | string[] }) => Promise<TargetEntity>;
class DefaultCrudRepository
class DefaultCrudRepository<T extends Entity, ID, Relations extends object = {}> implements EntityCrudRepository<T, ID, Relations> {}
Default implementation of CRUD repository using legacy juggler model and data source
constructor
constructor( entityClass: typeof Entity & { prototype: T }, dataSource: juggler.DataSource);
Constructor of DefaultCrudRepository
Parameter entityClass
LoopBack 4 entity class
Parameter dataSource
Legacy juggler data source
property dataSource
dataSource: juggler.DataSource;
property entityClass
entityClass: typeof Entity & { prototype: T };
property inclusionResolvers
readonly inclusionResolvers: Map<string, InclusionResolver<T, Entity>>;
property modelClass
modelClass: juggler.PersistedModelClass;
method count
count: (where?: Where<T>, options?: Options) => Promise<Count>;
method create
create: (entity: DataObject<T>, options?: Options) => Promise<T>;
method createAll
createAll: (entities: DataObject<T>[], options?: Options) => Promise<T[]>;
method createBelongsToAccessorFor
protected createBelongsToAccessorFor: <Target extends Entity, TargetId>( relationName: string, targetRepositoryGetter: any) => BelongsToAccessor<Target, ID>;
Function to create a belongs to accessor
Parameter relationName
Name of the relation defined on the source model
Parameter targetRepo
Target repository instance
method createHasManyRepositoryFactoryFor
protected createHasManyRepositoryFactoryFor: < Target extends Entity, TargetID, ForeignKeyType>( relationName: string, targetRepositoryGetter: Getter<EntityCrudRepository<Target, TargetID, {}>>) => HasManyRepositoryFactory<Target, ForeignKeyType>;
Function to create a constrained relation repository factory
Parameter relationName
Name of the relation defined on the source model
Parameter targetRepo
Target repository instance
Example 1
class CustomerRepository extends DefaultCrudRepository<Customer,typeof Customer.prototype.id,CustomerRelations> {public readonly orders: HasManyRepositoryFactory<Order, typeof Customer.prototype.id>;constructor(protected db: juggler.DataSource,orderRepository: EntityCrudRepository<Order, typeof Order.prototype.id>,) {super(Customer, db);this.orders = this._createHasManyRepositoryFactoryFor('orders',orderRepository,);}}
method createHasManyThroughRepositoryFactoryFor
protected createHasManyThroughRepositoryFactoryFor: < Target extends Entity, TargetID, Through extends Entity, ThroughID, ForeignKeyType>( relationName: string, targetRepositoryGetter: any, throughRepositoryGetter: Getter<EntityCrudRepository<Through, ThroughID, {}>>) => HasManyThroughRepositoryFactory<Target, TargetID, Through, ForeignKeyType>;
Function to create a constrained hasManyThrough relation repository factory
Parameter relationName
Name of the relation defined on the source model
Parameter targetRepo
Target repository instance
Parameter throughRepo
Through repository instance
Example 1
class CustomerRepository extends DefaultCrudRepository<Customer,typeof Customer.prototype.id,CustomerRelations> {public readonly cartItems: HasManyRepositoryFactory<CartItem, typeof Customer.prototype.id>;constructor(protected db: juggler.DataSource,cartItemRepository: EntityCrudRepository<CartItem, typeof, CartItem.prototype.id>,throughRepository: EntityCrudRepository<Through, typeof Through.prototype.id>,) {super(Customer, db);this.cartItems = this.createHasManyThroughRepositoryFactoryFor('cartItems',cartItemRepository,);}}
method createHasOneRepositoryFactoryFor
protected createHasOneRepositoryFactoryFor: < Target extends Entity, TargetID, ForeignKeyType>( relationName: string, targetRepositoryGetter: any) => HasOneRepositoryFactory<Target, ForeignKeyType>;
Function to create a constrained hasOne relation repository factory
Parameter relationName
Name of the relation defined on the source model
Parameter targetRepo
Target repository instance
method createReferencesManyAccessorFor
protected createReferencesManyAccessorFor: <Target extends Entity, TargetId>( relationName: string, targetRepoGetter: Getter<EntityCrudRepository<Target, TargetId, {}>>) => ReferencesManyAccessor<Target, ID>;
Function to create a references many accessor
Parameter relationName
Name of the relation defined on the source model
Parameter targetRepo
Target repository instance
method definePersistedModel
protected definePersistedModel: (entityClass: typeof Model) => any;
Creates a legacy persisted model class, attaches it to the datasource and returns it. This method can be overridden in sub-classes to acess methods and properties in the generated model class.
Parameter entityClass
LB4 Entity constructor
method delete
delete: (entity: T, options?: Options) => Promise<void>;
method deleteAll
deleteAll: (where?: Where<T>, options?: Options) => Promise<Count>;
method deleteById
deleteById: (id: ID, options?: Options) => Promise<void>;
method ensurePersistable
protected ensurePersistable: <R extends T>( entity: R | DataObject<R>, options?: {}) => legacy.ModelData<legacy.PersistedModel>;
Converts an entity object to a JSON object to check if it contains navigational property. Throws an error if
entity
contains navigational property.Parameter entity
The entity passed from CRUD operations' caller.
Parameter options
method entityToData
protected entityToData: <R extends T>( entity: R | DataObject<R>, options?: {}) => Promise<legacy.ModelData<legacy.PersistedModel>>;
This function works as a persist hook. It converts an entity from the CRUD operations' caller to a persistable data that can will be stored in the back-end database.
User can extend
DefaultCrudRepository
then override this function to execute custom persist hook.Parameter entity
The entity passed from CRUD operations' caller.
Parameter options
method execute
execute: { ( command: Command, parameters: NamedParameters | PositionalParameters, options?: Options ): Promise<AnyObject>; ( collectionName: string, command: string, ...parameters: PositionalParameters ): Promise<AnyObject>; (...args: PositionalParameters): Promise<AnyObject>;};
Execute a SQL command.
**WARNING:** In general, it is always better to perform database actions through repository methods. Directly executing SQL may lead to unexpected results, corrupted data, security vulnerabilities and other issues.
Parameter command
A parameterized SQL command or query. Check your database documentation for information on which characters to use as parameter placeholders.
Parameter parameters
List of parameter values to use.
Parameter options
Additional options, for example
transaction
.Returns
A promise which resolves to the command output as returned by the database driver. The output type (data structure) is database specific and often depends on the command executed.
Example 1
// MySQLconst result = await repo.execute('SELECT * FROM Products WHERE size > ?',[42]);// PostgreSQLconst result = await repo.execute('SELECT * FROM Products WHERE size > $1',[42]);Execute a MongoDB command.
**WARNING:** In general, it is always better to perform database actions through repository methods. Directly executing MongoDB commands may lead to unexpected results and other issues.
Parameter collectionName
The name of the collection to execute the command on.
Parameter command
The command name. See [Collection API docs](http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html) for the list of commands supported by the MongoDB client.
Parameter parameters
Command parameters (arguments), as described in MongoDB API docs for individual collection methods.
Returns
A promise which resolves to the command output as returned by the database driver.
Example 1
const result = await repo.execute('MyCollection', 'aggregate', [{$lookup: {// ...}},{$unwind: '$data'},{$out: 'tempData'}]);Execute a raw database command using a connector that's not described by LoopBack's
execute
API yet.**WARNING:** In general, it is always better to perform database actions through repository methods. Directly executing database commands may lead to unexpected results and other issues.
Parameter args
Command and parameters, please consult your connector's documentation to learn about supported commands and their parameters.
Returns
A promise which resolves to the command output as returned by the database driver.
method exists
exists: (id: ID, options?: Options) => Promise<boolean>;
method find
find: (filter?: Filter<T>, options?: Options) => Promise<(T & Relations)[]>;
method findById
findById: ( id: ID, filter?: FilterExcludingWhere<T>, options?: Options) => Promise<T & Relations>;
method findOne
findOne: ( filter?: Filter<T>, options?: Options) => Promise<(T & Relations) | null>;
method includeRelatedModels
protected includeRelatedModels: ( entities: T[], include?: InclusionFilter[], options?: Options) => Promise<(T & Relations)[]>;
Returns model instances that include related models of this repository that have a registered resolver.
Parameter entities
An array of entity instances or data
Parameter include
Inclusion filter
Parameter options
Options for the operations
method normalizeFilter
protected normalizeFilter: (filter?: Filter<T>) => legacy.Filter | undefined;
Removes juggler's "include" filter as it does not apply to LoopBack 4 relations.
Parameter filter
Query filter
method registerInclusionResolver
registerInclusionResolver: ( relationName: string, resolver: InclusionResolver<T, Entity>) => void;
Register an inclusion resolver for the related model name.
Parameter relationName
Name of the relation defined on the source model
Parameter resolver
Resolver function for getting related model entities
method replaceById
replaceById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
method save
save: (entity: T, options?: Options) => Promise<T>;
method toEntities
protected toEntities: <R extends T>(models: juggler.PersistedModel[]) => R[];
method toEntity
protected toEntity: <R extends T>(model: juggler.PersistedModel) => R;
method update
update: (entity: T, options?: Options) => Promise<void>;
method updateAll
updateAll: ( data: DataObject<T>, where?: Where<T>, options?: Options) => Promise<Count>;
method updateById
updateById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
class DefaultHasManyRepository
class DefaultHasManyRepository< TargetEntity extends Entity, TargetID, TargetRepository extends EntityCrudRepository<TargetEntity, TargetID>> implements HasManyRepository<TargetEntity> {}
constructor
constructor( getTargetRepository: Getter<TargetRepository>, constraint: DataObject<TargetEntity>);
Constructor of DefaultHasManyEntityCrudRepository
Parameter getTargetRepository
the getter of the related target model repository instance
Parameter constraint
the key value pair representing foreign key name to constrain the target repository instance
property constraint
constraint: DataObject<TargetEntity>;
property getTargetRepository
getTargetRepository: Getter<TargetRepository>;
method create
create: ( targetModelData: DataObject<TargetEntity>, options?: Options) => Promise<TargetEntity>;
method delete
delete: (where?: Where<TargetEntity>, options?: Options) => Promise<Count>;
method find
find: ( filter?: Filter<TargetEntity>, options?: Options) => Promise<TargetEntity[]>;
method patch
patch: ( dataObject: DataObject<TargetEntity>, where?: Where<TargetEntity>, options?: Options) => Promise<Count>;
class DefaultHasManyThroughRepository
class DefaultHasManyThroughRepository< TargetEntity extends Entity, TargetID, TargetRepository extends EntityCrudRepository<TargetEntity, TargetID>, ThroughEntity extends Entity, ThroughID, ThroughRepository extends EntityCrudRepository<ThroughEntity, ThroughID>> implements HasManyThroughRepository<TargetEntity, TargetID, ThroughEntity> {}
a class for CRUD operations for hasManyThrough relation.
Warning: The hasManyThrough interface is experimental and is subject to change. If backwards-incompatible changes are made, a new major version may not be released.
constructor
constructor( getTargetRepository: any, getThroughRepository: Getter<ThroughRepository>, getTargetConstraintFromThroughModels: ( throughInstances: ThroughEntity[] ) => DataObject<TargetEntity>, getTargetKeys: (throughInstances: ThroughEntity[]) => TargetID[], getThroughConstraintFromSource: () => DataObject<ThroughEntity>, getTargetIds: (targetInstances: TargetEntity[]) => TargetID[], getThroughConstraintFromTarget: ( targetID: TargetID[] ) => DataObject<ThroughEntity>, targetResolver: TypeResolver<Entity, typeof Entity>, throughResolver: TypeResolver<Entity, typeof Entity>);
property getTargetConstraintFromThroughModels
getTargetConstraintFromThroughModels: ( throughInstances: ThroughEntity[]) => DataObject<TargetEntity>;
property getTargetIds
getTargetIds: (targetInstances: TargetEntity[]) => TargetID[];
property getTargetKeys
getTargetKeys: (throughInstances: ThroughEntity[]) => TargetID[];
property getTargetRepository
getTargetRepository: any;
property getTargetRepositoryDict
getTargetRepositoryDict: { [repoType: string]: Getter<TargetRepository> };
property getThroughConstraintFromSource
getThroughConstraintFromSource: () => DataObject<ThroughEntity>;
property getThroughConstraintFromTarget
getThroughConstraintFromTarget: ( targetID: TargetID[]) => DataObject<ThroughEntity>;
property getThroughRepository
getThroughRepository: Getter<ThroughRepository>;
property targetResolver
targetResolver: TypeResolver<Entity, typeof Entity>;
property throughResolver
throughResolver: TypeResolver<Entity, typeof Entity>;
method create
create: ( targetModelData: DataObject<TargetEntity>, options?: Options & { throughData?: DataObject<ThroughEntity>; throughOptions?: Options; } & { polymorphicType?: string }) => Promise<TargetEntity>;
method delete
delete: ( where?: Where<TargetEntity>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { polymorphicType?: string | string[] }) => Promise<Count>;
method find
find: ( filter?: Filter<TargetEntity>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { polymorphicType?: string | string[] }) => Promise<TargetEntity[]>;
method link
link: ( targetId: TargetID, options?: Options & { throughData?: DataObject<ThroughEntity>; throughOptions?: Options; }) => Promise<void>;
method patch
patch: ( dataObject: | DataObject<TargetEntity> | { [polymorphicType: string]: DataObject<TargetEntity> }, where?: Where<TargetEntity>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { isPolymorphic?: boolean }) => Promise<Count>;
method unlink
unlink: ( targetId: TargetID, options?: Options & { throughOptions?: Options }) => Promise<void>;
method unlinkAll
unlinkAll: (options?: Options & { throughOptions?: Options }) => Promise<void>;
class DefaultHasOneRepository
class DefaultHasOneRepository< TargetEntity extends Entity, TargetID, TargetRepository extends EntityCrudRepository<TargetEntity, TargetID>> implements HasOneRepository<TargetEntity> {}
constructor
constructor( getTargetRepository: any, constraint: DataObject<TargetEntity>, targetResolver: TypeResolver<Entity, typeof Entity>);
Constructor of DefaultHasOneEntityCrudRepository
Parameter getTargetRepository
either a dictionary of target model type - target repository instance or a single target repository instance e.g. if the target is of a non-polymorphic type "Student", put the studentRepositoryGetterInstance if the target is of a polymorphic type "Person" which can be either a "Student" or a "Teacher" then put "{Student: studentRepositoryGetterInstance, Teacher: teacherRepositoryGetterInstance}"
Parameter constraint
the key value pair representing foreign key name to constrain the target repository instance
Parameter targetResolver
() => Target to resolve the target class e.g. if the target is of type "Student", then put "() => Student"
property constraint
constraint: DataObject<TargetEntity>;
property getTargetRepository
getTargetRepository: any;
property getTargetRepositoryDict
getTargetRepositoryDict: { [repoType: string]: Getter<TargetRepository> };
property targetResolver
targetResolver: TypeResolver<Entity, typeof Entity>;
method create
create: ( targetModelData: DataObject<TargetEntity>, options?: Options & { polymorphicType?: string }) => Promise<TargetEntity>;
method delete
delete: ( options?: Options & { polymorphicType?: string | string[] }) => Promise<Count>;
method get
get: ( filter?: Pick< Filter<TargetEntity>, Exclude<keyof Filter<TargetEntity>, 'where'> >, options?: Options & { polymorphicType?: string | string[] }) => Promise<TargetEntity>;
method patch
patch: ( dataObject: | DataObject<TargetEntity> | { [polymorphicType: string]: DataObject<TargetEntity> }, options?: Options & { isPolymorphic?: boolean }) => Promise<Count>;
class DefaultKeyValueRepository
class DefaultKeyValueRepository<T extends Model> implements KeyValueRepository<T> {}
An implementation of KeyValueRepository based on loopback-datasource-juggler
constructor
constructor( entityClass: typeof Model & { prototype: T }, ds: juggler.DataSource);
Construct a KeyValueRepository with a legacy DataSource
Parameter ds
Legacy DataSource
property kvModelClass
kvModelClass: any;
A legacy KeyValueModel class
method delete
delete: (key: string, options?: Options) => Promise<void>;
method deleteAll
deleteAll: (options?: Options) => Promise<void>;
method expire
expire: (key: string, ttl: number, options?: Options) => Promise<void>;
method get
get: (key: string, options?: Options) => Promise<T>;
method keys
keys: (filter?: KeyValueFilter, options?: Options) => AsyncIterable<string>;
method set
set: (key: string, value: DataObject<T>, options?: Options) => Promise<void>;
method toEntity
protected toEntity: (modelData: legacy.ModelData) => T;
method ttl
ttl: (key: string, options?: Options) => Promise<number>;
class DefaultReferencesManyRepository
class DefaultReferencesManyRepository< TargetEntity extends Entity, TargetIds, TargetRepository extends EntityCrudRepository<TargetEntity, TargetIds>> implements ReferencesManyRepository<TargetEntity> {}
constructor
constructor( getTargetRepository: Getter<TargetRepository>, constraint: DataObject<TargetEntity>);
Constructor of DefaultReferencesManyEntityCrudRepository
Parameter getTargetRepository
the getter of the related target model repository instance
Parameter constraint
the key value pair representing foreign key name to constrain the target repository instance
property constraint
constraint: DataObject<TargetEntity>;
property getTargetRepository
getTargetRepository: Getter<TargetRepository>;
method get
get: (options?: Options) => Promise<TargetEntity>;
class DefaultTransactionalRepository
class DefaultTransactionalRepository< T extends Entity, ID, Relations extends object = {} > extends DefaultCrudRepository<T, ID, Relations> implements TransactionalEntityRepository<T, ID, Relations> {}
Default implementation of CRUD repository using legacy juggler model and data source with beginTransaction() method for connectors which support Transactions
method beginTransaction
beginTransaction: (options?: IsolationLevel | Options) => Promise<Transaction>;
class Entity
class Entity extends Model implements Persistable {}
Base class for entities which have unique ids
method buildWhereForId
static buildWhereForId: (id: any) => any;
Build the where object for the given id
Parameter id
The id value
method getId
getId: () => any;
Get the identity value. If the identity is a composite key, returns an object.
method getIdObject
getIdObject: () => Object;
Get the identity as an object, such as
{id: 1}
or{schoolId: 1, studentId: 2}
method getIdOf
static getIdOf: (entityOrData: AnyObject) => any;
Get the identity value for a given entity instance or entity data object.
Parameter entityOrData
The data object for which to determine the identity value.
method getIdProperties
static getIdProperties: () => string[];
Get the names of identity properties (primary keys).
class EntityNotFoundError
class EntityNotFoundError<ID, Props extends object = {}> extends Error {}
constructor
constructor( entityOrName: string | typeof Entity, entityId: {}, extraProperties?: {});
property code
code: string;
property entityId
entityId: {};
property entityName
entityName: string;
class InvalidBodyError
class InvalidBodyError<ID, Props extends object = {}> extends Error {}
constructor
constructor( entityOrName: string | typeof Entity, entityId: {}, extraProperties?: {});
property code
code: string;
property entityId
entityId: {};
property entityName
entityName: string;
property statusCode
statusCode: number;
class InvalidPolymorphismError
class InvalidPolymorphismError<Props extends object = {}> extends Error {}
constructor
constructor(typeName: string, discriminator?: string, extraProperties?: {});
property code
code: string;
class InvalidRelationError
class InvalidRelationError<Props extends object = {}> extends Error {}
constructor
constructor( reason: string, relationMeta: RelationMetadata, extraProperties?: {});
property code
code: string;
property reason
reason: string;
property relationName
relationName: string;
property relationType
relationType: RelationType;
property sourceModelName
sourceModelName: string;
class Model
class Model {}
Base class for models
constructor
constructor(data?: DataObject<Model>);
property definition
static definition: ModelDefinition;
property modelName
static readonly modelName: string;
method toJSON
toJSON: () => Object;
Serialize into a plain JSON object
method toObject
toObject: (options?: Options) => Object;
Convert to a plain object as DTO
If
ignoreUnknownProperty
is set to false, convert all properties in the model instance, otherwise only convert the ones defined in the model definitions.See function
asObject
for each property's conversion rules.
class ModelDefinition
class ModelDefinition {}
Definition for a model
constructor
constructor(nameOrDef: string | ModelDefinitionSyntax);
property name
readonly name: string;
property properties
properties: { [name: string]: PropertyDefinition };
property relations
relations: RelationDefinitionMap;
property settings
settings: ModelSettings;
method addProperty
addProperty: ( name: string, definitionOrType: PropertyDefinition | PropertyType) => this;
Add a property
Parameter name
Property definition or name (string)
Parameter definitionOrType
Definition or property type
method addRelation
addRelation: (definition: RelationMetadata) => this;
Define a new relation.
Parameter definition
The definition of the new relation.
method addSetting
addSetting: (name: string, value: any) => this;
Add a setting
Parameter name
Setting name
Parameter value
Setting value
method belongsTo
belongsTo: ( name: string, definition: Omit<BelongsToDefinition, 'name' | 'type' | 'targetsMany'>) => this;
Define a new belongsTo relation.
Parameter name
The name of the belongsTo relation.
Parameter definition
The definition of the belongsTo relation.
method hasMany
hasMany: ( name: string, definition: Omit<HasManyDefinition, 'name' | 'type' | 'targetsMany'>) => this;
Define a new hasMany relation.
Parameter name
The name of the hasMany relation.
Parameter definition
The definition of the hasMany relation.
method hasOne
hasOne: ( name: string, definition: Omit<HasOneDefinition, 'name' | 'type' | 'targetsMany'>) => this;
Define a new hasOne relation.
Parameter name
The name of the hasOne relation.
Parameter definition
The definition of the hasOne relation.
method idProperties
idProperties: () => string[];
Get an array of names of ID properties, which are specified in the model settings or properties with
id
attribute.Example 1
{settings: {id: ['id']}properties: {id: {type: 'string',id: true}}}
method referencesMany
referencesMany: ( name: string, definition: Omit<ReferencesManyDefinition, 'name' | 'type' | 'targetsMany'>) => this;
Define a new referencesMany relation.
Parameter name
The name of the referencesMany relation.
Parameter definition
The definition of the referencesMany relation.
class ModelMetadataHelper
class ModelMetadataHelper {}
method getModelMetadata
static getModelMetadata: ( target: Function, options?: InspectionOptions) => ModelDefinition | {};
A utility function to simplify retrieving metadata from a target model and its properties.
Parameter target
The class from which to retrieve metadata.
Parameter options
An options object for the MetadataInspector to customize the output of the metadata retrieval functions.
class ModelType
class ModelType<T extends Model> extends ObjectType<T> {}
Model type
constructor
constructor(modelClass: Class<T>);
property modelClass
modelClass: Class<T>;
property name
readonly name: string;
method serialize
serialize: (value: T | null | undefined) => Object | null | undefined;
class NullType
class NullType implements Type<null> {}
Null type
property name
readonly name: string;
method coerce
coerce: (value: any) => null;
method defaultValue
defaultValue: () => null;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: boolean | null | undefined) => null;
class NumberType
class NumberType implements Type<number> {}
Number type
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => number;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: number | null | undefined) => number | null | undefined;
class ObjectType
class ObjectType<T extends AnyObject> implements Type<T> {}
Object type
constructor
constructor(type: Class<T>);
property name
name: string;
property type
type: Class<T>;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => T;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: T | null | undefined) => any;
class RepositoryMetadata
class RepositoryMetadata {}
Metadata for a repository
constructor
constructor(modelOrRepo: string | typeof Entity, dataSource?: any);
Constructor for RepositoryMetadata
Parameter modelOrRepo
Name or class of the model. If the value is a string and
dataSource
is not present, it will treated as the name of a predefined repositoryParameter dataSource
Name or instance of the data source
For example:
- new RepositoryMetadata(repoName); - new RepositoryMetadata(modelName, dataSourceName); - new RepositoryMetadata(modelClass, dataSourceInstance); - new RepositoryMetadata(modelName, dataSourceInstance); - new RepositoryMetadata(modelClass, dataSourceName);
property dataSource
dataSource?: any;
Instance of the data source
property dataSourceName
dataSourceName?: string;
Name of the data source
property modelClass
modelClass?: typeof Entity;
Class of the model
property modelName
modelName?: string;
Name of the model
property name
name?: string;
Name of the predefined repository
class RepositoryMixinDoc
class RepositoryMixinDoc {}
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 RepositoryMixin
constructor
constructor(...args: any[]);
method component
component: (component: Class<{}>) => Binding;
Add a component to this application. Also mounts all the components repositories.
Parameter component
The component to add.
Example 1
export class ProductComponent {controllers = [ProductController];repositories = [ProductRepo, UserRepo];providers = {[AUTHENTICATION_STRATEGY]: AuthStrategy,[AUTHORIZATION_ROLE]: Role,};};app.component(ProductComponent);
method dataSource
dataSource: ( dataSource: Class<juggler.DataSource> | juggler.DataSource, name?: string) => Binding;
Add the dataSource to this application.
Parameter dataSource
The dataSource to add.
Parameter name
The binding name of the datasource; defaults to dataSource.name
Example 1
const ds: juggler.DataSource = new juggler.DataSource({name: 'db',connector: 'memory',});app.dataSource(ds);// The datasource can be injected withconstructor(@inject('datasources.db') dataSource: DataSourceType) {}
method getRepository
getRepository: <R extends Repository<any>>(repo: Class<R>) => Promise<R>;
Retrieve the repository instance from the given Repository class
Parameter repo
The repository class to retrieve the instance of
method migrateSchema
migrateSchema: (options?: SchemaMigrationOptions) => Promise<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!
Parameter options
Migration options, e.g. whether to update tables preserving data or rebuild everything from scratch.
method mountComponentRepository
mountComponentRepository: (component: Class<{}>) => void;
Get an instance of a component and mount all it's repositories. This function is intended to be used internally by component()
Parameter component
The component to mount repositories of
method repository
repository: (repo: Class<Repository<any>>) => Binding;
Add a repository to this application.
Parameter repo
The repository to add.
Example 1
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);
class StringType
class StringType implements Type<string> {}
String type
property name
readonly name: string;
method coerce
coerce: (value: any) => string;
method defaultValue
defaultValue: () => string;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: string | null | undefined) => string | null | undefined;
class UnionType
class UnionType implements Type<any> {}
Union type, such as string | number
constructor
constructor(itemTypes: Type<any>[]);
property itemTypes
itemTypes: Type<any>[];
property name
readonly name: string;
method coerce
coerce: (value: any) => any;
method defaultValue
defaultValue: () => any;
method isCoercible
isCoercible: (value: any) => boolean;
method isInstance
isInstance: (value: any) => boolean;
method serialize
serialize: (value: any) => any;
class ValueObject
abstract class ValueObject extends Model implements Persistable {}
Base class for value objects - An object that contains attributes but has no conceptual identity. They should be treated as immutable.
Interfaces
interface AnyObject
interface AnyObject {}
Objects with open properties
index signature
[property: string]: any;
interface ApplicationWithRepositories
interface ApplicationWithRepositories extends Application {}
Interface for an Application mixed in with RepositoryMixin
method component
component: (component: Class<unknown>, name?: string) => Binding;
method dataSource
dataSource: <D extends juggler.DataSource>( dataSource: Class<D> | D, name?: string) => Binding<D>;
method getRepository
getRepository: <R extends Repository<any>>(repo: Class<R>) => Promise<R>;
method migrateSchema
migrateSchema: (options?: SchemaMigrationOptions) => Promise<void>;
method model
model: <M extends Class<unknown>>(modelClass: M) => Binding<M>;
method mountComponentRepositories
mountComponentRepositories: (component: Class<unknown>) => void;
method repository
repository: <R extends Repository<any>>( repo: Class<R>, name?: string) => Binding<R>;
interface BaseRepositoryClass
interface BaseRepositoryClass< M extends typeof Model, R extends Repository<PrototypeOf<M>>> {}
Signature for repository classes that can be used as the base class for
define*
functions. The constructor of a base repository class accepts the target model constructor and the datasource to use.define*
functions require a class implementing this interface on input.
property prototype
prototype: R;
construct signature
new (modelClass: M, dataSource: juggler.DataSource): R;
The constructor for the generated repository class
Parameter modelClass
Model class
Parameter dataSource
DataSource object
interface BelongsToAccessor
interface BelongsToAccessor<Target extends Entity, SourceId> {}
property inclusionResolver
inclusionResolver: InclusionResolver<Entity, Target>;
Use
resolver
property to obtain an InclusionResolver for this relation.
call signature
(sourceId: SourceId, polymorphicTypes?: string | string[]): Promise<Target>;
Invoke the function to obtain HasManyRepository.
interface BelongsToDefinition
interface BelongsToDefinition extends RelationDefinitionBase {}
property keyFrom
keyFrom?: string;
property keyTo
keyTo?: string;
property polymorphic
polymorphic?: | boolean | { discriminator: string; };
The polymorphism of the target model. The discriminator is a key of source model. If the target model is not polymorphic, then the value should be left undefined or false; If the key on source model indicating the concrete class of the target instance is default i.e. camelCase(classNameOf(throughModelInstance)) + "Id" Then the discriminator field can be undefined
property targetsMany
targetsMany: false;
property type
type: RelationType.belongsTo;
interface BelongsToRepository
interface BelongsToRepository<Target extends Entity> {}
CRUD operations for a target repository of a BelongsTo relation
method get
get: ( options?: Options & { polymorphicType?: string | string[] }) => Promise<Target>;
Gets the target model instance
Parameter options
options.polymorphicType - a string or a string array of polymorphic type names to specify which repositories should are expected to be searched It is highly recommended to contain this param especially for datasources using deplicated ids across tables
Returns
A promise resolved with the target object or rejected with an EntityNotFoundError when target model instance was not found.
interface Class
interface Class<T> {}
Interface for classes with
new
operator and static properties/methods
construct signature
new (...args: any[]): T;
index signature
[property: string]: any;
interface Connector
interface Connector {}
Common properties/operations for connectors
property configModel
configModel?: Model;
property interfaces
interfaces?: ( | string | ConnectorInterfaces.StrongRelation | ConnectorInterfaces.StrongJoins)[];
property name
name: string;
method connect
connect: () => Promise<void>;
method disconnect
disconnect: () => Promise<void>;
method execute
execute: ( command: Command, parameters: NamedParameters | PositionalParameters, options?: Options) => Promise<AnyObject>;
method ping
ping: () => Promise<void>;
interface ConstructorFunction
interface ConstructorFunction<T> {}
Interface for constructor functions without
new
operator.Example 1
function Foo(x) {if (!(this instanceof Foo)) { return new Foo(x); }this.x = x;}
call signature
(...args: any[]): T;
interface Count
interface Count {}
Count of Model instances that were successful for methods like
updateAll
,deleteAll
, etc.
property count
count: number;
interface CrudConnector
interface CrudConnector extends Connector {}
CRUD operations for connector implementations
method count
count: ( modelClass: Class<Entity>, where?: Where<Entity>, options?: Options) => Promise<Count>;
Count matching entities
Parameter modelClass
The model class
Parameter where
The matching criteria
Parameter options
Options for the operation
Returns
A promise of number of matching entities
method create
create: ( modelClass: Class<Entity>, entity: EntityData, options?: Options) => Promise<EntityData>;
Create a new entity
Parameter modelClass
The model class
Parameter entity
The entity instance or data
Parameter options
Options for the operation
Returns
A promise of the entity created
method createAll
createAll: ( modelClass: Class<Entity>, entities: EntityData[], options?: Options) => Promise<EntityData[]>;
Create multiple entities
Parameter modelClass
The model class
Parameter entities
An array of entity instances or data
Parameter options
Options for the operation
Returns
A promise of an array of entities created
method delete
delete: ( modelClass: Class<Entity>, entity: EntityData, options?: Options) => Promise<boolean>;
Delete an entity
Parameter modelClass
The model class
Parameter entity
The entity instance or data
Parameter options
Options for the operation
Returns
Promise if an entity is deleted, otherwise Promise
method deleteAll
deleteAll: ( modelClass: Class<Entity>, where?: Where<Entity>, options?: Options) => Promise<Count>;
Delete matching entities
Parameter modelClass
The model class
Parameter where
The matching criteria
Parameter options
Options for the operation
Returns
A promise of number of matching entities deleted
method deleteById
deleteById: <IdType>( modelClass: Class<Entity>, id: IdType, options?: Options) => Promise<boolean>;
Delete an entity by id
Parameter modelClass
The model class
Parameter id
The entity id value
Parameter options
Options for the operation
Returns
Promise if an entity is deleted for the id, otherwise Promise
method exists
exists: <IdType>( modelClass: Class<Entity>, id: IdType, options?: Options) => Promise<boolean>;
Check if an entity exists for the id
Parameter modelClass
The model class
Parameter id
The entity id value
Parameter options
Options for the operation
Returns
Promise if an entity exists for the id, otherwise Promise
method find
find: ( modelClass: Class<Entity>, filter?: Filter, options?: Options) => Promise<EntityData[]>;
Find matching entities by the filter
Parameter modelClass
The model class
Parameter filter
The query filter
Parameter options
Options for the operation
Returns
A promise of an array of entities found for the filter
method findById
findById: <IdType>( modelClass: Class<Entity>, id: IdType, options?: Options) => Promise<EntityData>;
Find an entity by id
Parameter modelClass
The model class
Parameter id
The entity id value
Parameter options
Options for the operation
Returns
A promise of the entity found for the id
method replaceById
replaceById: <IdType>( modelClass: Class<Entity>, id: IdType, data: EntityData, options?: Options) => Promise<boolean>;
Replace an entity by id
Parameter modelClass
The model class
Parameter id
The entity id value
Parameter data
The data attributes to be updated
Parameter options
Options for the operation
Returns
Promise if an entity is replaced for the id, otherwise Promise
method save
save: ( modelClass: Class<Entity>, entity: EntityData, options?: Options) => Promise<EntityData>;
Save an entity
Parameter modelClass
The model class
Parameter entity
The entity instance or data
Parameter options
Options for the operation
Returns
A promise of the entity saved
method update
update: ( modelClass: Class<Entity>, entity: EntityData, options?: Options) => Promise<boolean>;
Update an entity
Parameter modelClass
The model class
Parameter entity
The entity instance or data
Parameter options
Options for the operation
Returns
Promise if an entity is updated, otherwise Promise
method updateAll
updateAll: ( modelClass: Class<Entity>, data: EntityData, where?: Where<Entity>, options?: Options) => Promise<Count>;
Update matching entities
Parameter modelClass
The model class
Parameter data
The data attributes to be updated
Parameter where
The matching criteria
Parameter options
Options for the operation
Returns
A promise of number of matching entities deleted
method updateById
updateById: <IdType>( modelClass: Class<Entity>, id: IdType, data: EntityData, options?: Options) => Promise<boolean>;
Update an entity by id
Parameter modelClass
The model class
Parameter id
The entity id value
Parameter data
The data attributes to be updated
Parameter options
Options for the operation
Returns
Promise if an entity is updated for the id, otherwise Promise
interface CrudRepository
interface CrudRepository< T extends ValueObject | Entity, Relations extends object = {}> extends Repository<T> {}
Basic CRUD operations for ValueObject and Entity. No ID is required.
method count
count: (where?: Where<T>, options?: Options) => Promise<Count>;
Count matching records
Parameter where
Matching criteria
Parameter options
Options for the operations
Returns
A promise of number of records matched
method create
create: (dataObject: DataObject<T>, options?: Options) => Promise<T>;
Create a new record
Parameter dataObject
The data to be created
Parameter options
Options for the operations
Returns
A promise of record created
method createAll
createAll: (dataObjects: DataObject<T>[], options?: Options) => Promise<T[]>;
Create all records
Parameter dataObjects
An array of data to be created
Parameter options
Options for the operations
Returns
A promise of an array of records created
method deleteAll
deleteAll: (where?: Where<T>, options?: Options) => Promise<Count>;
Delete matching records
Parameter where
Matching criteria
Parameter options
Options for the operations
Returns
A promise of number of records deleted
method find
find: (filter?: Filter<T>, options?: Options) => Promise<(T & Relations)[]>;
Find matching records
Parameter filter
Query filter
Parameter options
Options for the operations
Returns
A promise of an array of records found
method updateAll
updateAll: ( dataObject: DataObject<T>, where?: Where<T>, options?: Options) => Promise<Count>;
Updating matching records with attributes from the data object
Parameter dataObject
The data to be updated
Parameter where
Matching criteria
Parameter options
Options for the operations
Returns
A promise of number of records updated
interface DataSource
interface DataSource {}
DataSource denotes a configured connector
property connector
connector?: Connector;
property name
name: string;
property settings
settings: AnyObject;
index signature
[property: string]: any;
interface EntityCrudRepository
interface EntityCrudRepository<T extends Entity, ID, Relations extends object = {}> extends EntityRepository<T, ID>, CrudRepository<T, Relations> {}
CRUD operations for a repository of entities
property entityClass
entityClass: typeof Entity & { prototype: T;};
property inclusionResolvers
inclusionResolvers: Map<string, InclusionResolver<T, Entity>>;
method delete
delete: (entity: DataObject<T>, options?: Options) => Promise<void>;
Delete an entity
Parameter entity
Entity to be deleted
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
method deleteById
deleteById: (id: ID, options?: Options) => Promise<void>;
Delete an entity by id
Parameter id
Value for the entity id
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
method exists
exists: (id: ID, options?: Options) => Promise<boolean>;
Check if an entity exists for the given id
Parameter id
Value for the entity id
Parameter options
Options for the operations
Returns
Promise if an entity exists for the id, otherwise Promise
method findById
findById: ( id: ID, filter?: FilterExcludingWhere<T>, options?: Options) => Promise<T & Relations>;
Find an entity by id, return a rejected promise if not found.
Parameter id
Value for the entity id
Parameter filter
Additional query options. E.g.
filter.include
configures which related models to fetch as part of the database query (or queries).Parameter options
Options for the operations
Returns
A promise of an entity found for the id
Remarks
The rationale behind findById is to find an instance by its primary key (id). No other search criteria than id should be used. If a client wants to use a
where
clause beyond id, usefind
orfindOne
instead.
method replaceById
replaceById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
Replace an entity by id
Parameter id
Value for the entity id
Parameter data
Data attributes to be replaced
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
method save
save: (entity: DataObject<T>, options?: Options) => Promise<T>;
Save an entity. If no id is present, create a new entity
Parameter entity
Entity to be saved
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
method update
update: (entity: DataObject<T>, options?: Options) => Promise<void>;
Update an entity
Parameter entity
Entity to be updated
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
method updateById
updateById: (id: ID, data: DataObject<T>, options?: Options) => Promise<void>;
Update an entity by id with property/value pairs in the data object
Parameter id
Value for the entity id
Parameter data
Data attributes to be updated
Parameter options
Options for the operations
Returns
A promise that will be resolve if the operation succeeded or will be rejected if the entity was not found.
interface EntityRepository
interface EntityRepository<T extends Entity, ID> extends ExecutableRepository<T> {}
Base interface for a repository of entities
interface ExecutableRepository
interface ExecutableRepository<T extends Model> extends Repository<T> {}
method execute
execute: ( command: Command, parameters: NamedParameters | PositionalParameters, options?: Options) => Promise<AnyObject>;
Execute a query with the given parameter object or an array of parameters
Parameter command
The query string or command object
Parameter parameters
The object with name/value pairs or an array of parameter values
Parameter options
Options
interface HasManyDefinition
interface HasManyDefinition extends RelationDefinitionBase {}
HasManyDefinition defines one-to-many relations and also possible defines many-to-many relations with through models.
property keyFrom
keyFrom?: string;
property keyTo
keyTo?: string;
keyTo: The foreign key used by the target model for this relation. keyFrom: The source key used by the source model for this relation.
E.g. when a Customer has many Order instances, then keyTo is "customerId". Note that "customerId" is the default FK assumed by the framework, users can provide a custom FK name by setting "keyTo". And Customer.id is keyFrom. keyFrom defaults to the id property of a model. Users can provide a custom source key name by setting "keyTo".
property targetsMany
targetsMany: true;
property through
through?: { /** * The through model of this relation. * * E.g. when a Category has many CategoryProductLink instances and a Product has many CategoryProductLink instances, * then CategoryProductLink is through. */ model: TypeResolver<Entity, typeof Entity>; /** * The foreign key of the source model defined in the through model, e.g. CategoryProductLink#categoryId */ keyFrom?: string; /** * The foreign key of the target model defined in the through model, e.g. CategoryProductLink#productId */ keyTo?: string; /** * The polymorphism of the target model. The discriminator is a key of *through* model. * If the target model is not polymorphic, then the value should be left undefined or false; * If the key on through model indicating the concrete class of the through instance is default * i.e. camelCase(classNameOf(targetModelInstance)) + "Id" * then the discriminator field can be undefined * * With current architecture design, polymorphic type cannot be supported without through * Consider using Source hasMany Through hasOne Target(polymorphic) * or Source hasMany Through belongsTo Target(polymorphic) for one-to-many relations */ polymorphic?: | boolean | { discriminator: string; };};
Description of the through model of the hasManyThrough relation.
A
hasManyThrough
relation defines a many-to-many connection with another model. This relation indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.E.g a Category has many Products, and a Product can have many Categories. CategoryProductLink can be the through model. Such a through model has information of foreign keys of the source model(Category) and the target model(Product).
Warning: The hasManyThrough interface is experimental and is subject to change. If backwards-incompatible changes are made, a new major version may not be released.
property type
type: RelationType.hasMany;
interface HasManyRepository
interface HasManyRepository<Target extends Entity> {}
CRUD operations for a target repository of a HasMany relation
method create
create: ( targetModelData: DataObject<Target>, options?: Options) => Promise<Target>;
Create a target model instance
Parameter targetModelData
The target model data
Parameter options
Options for the operation
Returns
A promise which resolves to the newly created target model instance
method delete
delete: (where?: Where<Target>, options?: Options) => Promise<Count>;
Delete multiple target model instances
Parameter where
Instances within the where scope are deleted
Parameter options
Returns
A promise which resolves the deleted target model instances
method find
find: (filter?: Filter<Target>, options?: Options) => Promise<Target[]>;
Find target model instance(s)
Parameter filter
A filter object for where, order, limit, etc.
Parameter options
Options for the operation
Returns
A promise which resolves with the found target instance(s)
method patch
patch: ( dataObject: DataObject<Target>, where?: Where<Target>, options?: Options) => Promise<Count>;
Patch multiple target model instances
Parameter dataObject
The fields and their new values to patch
Parameter where
Instances within the where scope are patched
Parameter options
Returns
A promise which resolves the patched target model instances
interface HasManyRepositoryFactory
interface HasManyRepositoryFactory<Target extends Entity, ForeignKeyType> {}
property inclusionResolver
inclusionResolver: InclusionResolver<Entity, Target>;
Use
resolver
property to obtain an InclusionResolver for this relation.
call signature
(fkValue: ForeignKeyType): HasManyRepository<Target>;
Invoke the function to obtain HasManyRepository.
interface HasManyThroughRepository
interface HasManyThroughRepository< Target extends Entity, TargetID, Through extends Entity> {}
CRUD operations for a target repository of a HasManyThrough relation
EXPERIMENTAL: This interface is not stable and may change in the near future. Backwards-incompatible changes may be introduced in semver-minor versions.
method create
create: ( targetModelData: DataObject<Target>, options?: Options & { throughData?: DataObject<Through>; throughOptions?: Options; } & { polymorphicType?: string }) => Promise<Target>;
Create a target model instance
Parameter targetModelData
The target model data
Parameter options
Options for the operation options.polymorphicType a string or a string array of polymorphic type names specify of which concrete model the created instance should be
Returns
A promise which resolves to the newly created target model instance
method delete
delete: ( where?: Where<Target>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { polymorphicType?: string | string[] }) => Promise<Count>;
Delete multiple target model instances
Parameter where
Instances within the where scope are deleted
Parameter options
options.throughOptions.discriminator - target discriminator field on through options.polymorphicType a string or a string array of polymorphic type names to specify which repositories should are expected to be searched It is highly recommended to contain this param especially for datasources using deplicated ids across tables
Returns
A promise which resolves the deleted target model instances
method find
find: ( filter?: Filter<Target>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { polymorphicType?: string | string[] }) => Promise<Target[]>;
Find target model instance(s)
Parameter filter
A filter object for where, order, limit, etc.
Parameter options
Options for the operation options.throughOptions.discriminator - target discriminator field on through options.polymorphicType a string or a string array of polymorphic type names to specify which repositories should are expected to be searched It is highly recommended to contain this param especially for datasources using deplicated ids across tables
Returns
A promise which resolves with the found target instance(s)
method link
link: ( targetModelId: TargetID, options?: Options & { throughData?: DataObject<Through>; throughOptions?: Options; }) => Promise<void>;
Creates a new many-to-many association to an existing target model instance
Parameter targetModelId
The target model ID to link
Parameter options
Returns
A promise which resolves to the linked target model instance
method patch
patch: ( dataObject: | DataObject<Target> | { [polymorphicType: string]: DataObject<Target> }, where?: Where<Target>, options?: Options & { throughOptions?: Options & { discriminator?: string }; } & { isPolymorphic?: boolean }) => Promise<Count>;
Patch multiple target model instances
Parameter dataObject
The fields and their new values to patch
Parameter where
Instances within the where scope are patched
Parameter options
options.throughOptions.discriminator - target discriminator field on through options.isPolymorphic - whether dataObject is a dictionary
Returns
A promise which resolves the patched target model instances
method unlink
unlink: ( targetModelId: TargetID, options?: Options & { throughOptions?: Options }) => Promise<void>;
Removes an association to an existing target model instance
Parameter targetModelId
The target model to unlink
Parameter options
Returns
A promise which resolves to null
method unlinkAll
unlinkAll: (options?: Options & { throughOptions?: Options }) => Promise<void>;
Remove all association to an existing target model instance
Parameter options
A promise which resolves to void
interface HasOneDefinition
interface HasOneDefinition extends RelationDefinitionBase {}
property keyFrom
keyFrom?: string;
property keyTo
keyTo?: string;
keyTo: The foreign key used by the target model for this relation. keyFrom: The source key used by the source model for this relation.
E.g. when a Customer has one Address instance, then keyTo is "customerId". Note that "customerId" is the default FK assumed by the framework, users can provide a custom FK name by setting "keyTo". And Customer.id is keyFrom. keyFrom defaults to the id property of a model. Users can provide a custom source key name by setting "keyTo".
property polymorphic
polymorphic?: | boolean | { discriminator: string; };
The polymorphism of the target model. The discriminator is a key of source model. If the target model is not polymorphic, then the value should be left undefined or false; If the key on source model indicating the concrete class of the target instance is default i.e. camelCase(classNameOf(throughModelInstance)) + "Id" Then the discriminator field can be undefined
property targetsMany
targetsMany: false;
property type
type: RelationType.hasOne;
interface HasOneRepository
interface HasOneRepository<Target extends Entity> {}
CRUD operations for a target repository of a HasMany relation
method create
create: ( targetModelData: DataObject<Target>, options?: Options & { polymorphicType?: string }) => Promise<Target>;
Create a target model instance
Parameter targetModelData
The target model data
Parameter options
Options for the operation options.polymorphicType - If polymorphic target model, specify of which concrete model the created instance should be
Returns
A promise which resolves to the newly created target model instance
method delete
delete: ( options?: Options & { polymorphicType?: string | string[] }) => Promise<Count>;
Delete the related target model instance
Parameter options
options.polymorphicType - a string or a string array of polymorphic type names to specify which repositories should are expected to be searched It is highly recommended to contain this param especially for datasources using deplicated ids across tables
Returns
A promise which resolves the deleted target model instances
method get
get: ( filter?: Pick<Filter<Target>, Exclude<keyof Filter<Target>, 'where'>>, options?: Options & { polymorphicType?: string | string[] }) => Promise<Target>;
Find the only target model instance that belongs to the declaring model.
Parameter filter
Query filter without a Where condition
Parameter options
Options for the operations options.polymorphicType - a string or a string array of polymorphic type names to specify which repositories should are expected to be searched It is highly recommended to contain this param especially for datasources using deplicated ids across tables
Returns
A promise resolved with the target object or rejected with an EntityNotFoundError when target model instance was not found.
method patch
patch: ( dataObject: | DataObject<Target> | { [polymorphicType: string]: DataObject<Target> }, options?: Options & { isPolymorphic?: boolean }) => Promise<Count>;
Patch the related target model instance
Parameter dataObject
The target model fields and their new values to patch If the target models are of different types, this should be a dictionary
Parameter options
options.isPolymorphic - whether dataObject is a dictionary
Returns
A promise which resolves the patched target model instances
interface HasOneRepositoryFactory
interface HasOneRepositoryFactory<Target extends Entity, ForeignKeyType> {}
property inclusionResolver
inclusionResolver: InclusionResolver<Entity, Target>;
Use
resolver
property to obtain an InclusionResolver for this relation.
call signature
(fkValue: ForeignKeyType): HasOneRepository<Target>;
Invoke the function to obtain HasOneRepository.
interface JsonSchemaWithExtensions
interface JsonSchemaWithExtensions extends JsonSchema {}
This module defines the key classes representing building blocks for Domain Driven Design. See https://en.wikipedia.org/wiki/Domain-driven_design#Building_blocks
index signature
[attributes: string]: any;
interface KeyValueRepository
interface KeyValueRepository<T extends Model> extends Repository<T> {}
Key/Value operations for connector implementations
method delete
delete: (key: string, options?: Options) => Promise<void>;
Delete an entry by key
Parameter key
Key for the entry
Parameter options
Options for the operation
method deleteAll
deleteAll: (options?: Options) => Promise<void>;
Delete all entries
Parameter key
Key for the entry
Parameter options
Options for the operation
method expire
expire: (key: string, ttl: number, options?: Options) => Promise<void>;
Set up ttl for an entry by key
Parameter key
Key for the entry
Parameter ttl
Ttl for the entry
Parameter options
Options for the operation
method get
get: (key: string, options?: Options) => Promise<T>;
Get an entry by key
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
A promise of the entry
method keys
keys: (filter?: KeyValueFilter, options?: Options) => AsyncIterable<string>;
Get an Iterator for matching keys
Parameter filter
Filter for keys
Parameter options
Options for the operation
Returns
An async iteratable iterator of keys so that the return value can be used with
for-await-of
.
method set
set: (key: string, value: DataObject<T>, options?: Options) => Promise<void>;
Set an entry with key/value
Parameter key
Key for the entry
Parameter value
Value for the entry
Parameter options
Options for the operation
method ttl
ttl: (key: string, options?: Options) => Promise<number>;
Get ttl for an entry by key
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
A promise of the TTL value
interface KVConnector
interface KVConnector<T extends Entity> extends Connector {}
Key/Value operations for connector implementations
method delete
delete: ( modelClass: Class<Entity>, key: string, options?: Options) => Promise<boolean>;
Delete an entry by key
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
Promise if an entry is deleted for the id, otherwise Promise
method deleteAll
deleteAll: (modelClass: Class<Entity>, options?: Options) => Promise<number>;
Delete all entries
Parameter modelClass
Model class
Parameter options
Options for the operation
Returns
A promise of the number of entries deleted
method expire
expire: ( modelClass: Class<Entity>, key: string, ttl: number, options?: Options) => Promise<boolean>;
Set up ttl for an entry by key
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
Promise if an entry is configured for the key, otherwise Promise
method get
get: (modelClass: Class<Entity>, key: string, options?: Options) => Promise<T>;
Get an entry by key
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
A promise of the entry found for the key
method iterateKeys
iterateKeys: ( modelClass: Class<Entity>, filter?: Filter, options?: Options) => Promise<Iterator<T>>;
Get an Iterator for matching keys
Parameter modelClass
Model class
Parameter filter
Matching filter
Parameter options
Options for the operation
Returns
A promise of an iterator of entries
method keys
keys: (modelClass: Class<Entity>, options?: Options) => Promise<string[]>;
Fetch all keys
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter options
Options for the operation
Returns
A promise of an array of keys for all entries
method set
set: ( modelClass: Class<Entity>, key: string, value: EntityData, options?: Options) => Promise<boolean>;
Set an entry with key/value
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter value
Value for the entry
Parameter options
Options for the operation
Returns
Promise if an entry is set for the key, otherwise Promise
method ttl
ttl: ( modelClass: Class<Entity>, key: string, ttl: number, options?: Options) => Promise<number>;
Get ttl for an entry by key
Parameter modelClass
Model class
Parameter key
Key for the entry
Parameter ttl
Time to live in millisenconds
Parameter options
Options for the operation
Returns
A promise of the TTL value
interface ModelDefinitionSyntax
interface ModelDefinitionSyntax {}
DSL for building a model definition.
property jsonSchema
jsonSchema?: JsonSchemaWithExtensions;
property name
name: string;
property properties
properties?: { [name: string]: PropertyDefinition | PropertyType;};
property relations
relations?: RelationDefinitionMap;
property settings
settings?: ModelSettings;
index signature
[attribute: string]: any;
interface ModelRepositoryClass
interface ModelRepositoryClass<M extends Model, R extends Repository<M>> {}
Signature for a Repository class bound to a given model. The constructor accepts only the dataSource to use for persistence.
define*
functions return a class implementing this interface.
property prototype
prototype: R;
construct signature
new (dataSource: juggler.DataSource): R;
The constructor for the generated repository class
Parameter dataSource
DataSource object
interface ModelSettings
interface ModelSettings {}
Defining the settings for a model See https://loopback.io/doc/en/lb4/Model.html#supported-entries-of-model-definition
property description
description?: string;
Description of the model
property forceId
forceId?: boolean;
Prevent clients from setting the auto-generated ID value manually
property hiddenProperties
hiddenProperties?: string[];
Hides properties from response bodies
property scope
scope?: object;
Scope enables you to set a scope that will apply to every query made by the model's repository
property strict
strict?: boolean | 'filter';
Specifies whether the model accepts only predefined properties or not
index signature
[name: string]: any;
interface Persistable
interface Persistable {}
interface PropertyDefinition
interface PropertyDefinition {}
Property definition for a model
property hidden
hidden?: boolean;
Used to hide this property from the response body, adding this property to the hiddenProperties array
property id
id?: boolean | number;
property itemType
itemType?: PropertyType;
property json
json?: PropertyForm;
property jsonSchema
jsonSchema?: JsonSchemaWithExtensions;
property store
store?: PropertyForm;
property type
type: PropertyType;
index signature
[attribute: string]: any;
interface PropertyForm
interface PropertyForm {}
See https://github.com/loopbackio/loopback-datasource-juggler/issues/432
interface ReferencesManyAccessor
interface ReferencesManyAccessor<Target extends Entity, SourceId> {}
property inclusionResolver
inclusionResolver: InclusionResolver<Entity, Target>;
Use
resolver
property to obtain an InclusionResolver for this relation.
call signature
(sourceId: SourceId): Promise<Target>;
Invoke the function to obtain HasManyRepository.
interface ReferencesManyDefinition
interface ReferencesManyDefinition extends RelationDefinitionBase {}
property keyFrom
keyFrom?: string;
property keyTo
keyTo?: string;
keyTo: The foreign key used by the target model for this relation. keyFrom: The source key used by the source model for this relation.
TODO(bajtos) Add relation description.
property targetsMany
targetsMany: true;
property type
type: RelationType.referencesMany;
interface ReferencesManyRepository
interface ReferencesManyRepository<Target extends Entity> {}
CRUD operations for a target repository of a ReferencesMany relation
method get
get: (options?: Options) => Promise<Target>;
Gets the target model instance
Parameter options
Returns
A promise resolved with the target object or rejected with an EntityNotFoundError when target model instance was not found.
interface RelationDefinitionBase
interface RelationDefinitionBase {}
property name
name: string;
The relation name, typically matching the name of the accessor property defined on the source model. For example "orders" or "customer".
property source
source: typeof Entity;
The source model of this relation.
E.g. when a Customer has many Order instances, then Customer is the source.
property target
target: TypeResolver<Entity, typeof Entity>;
The target model of this relation.
E.g. when a Customer has many Order instances, then Order is the target.
property targetsMany
targetsMany: boolean;
True for relations targeting multiple instances (e.g. HasMany), false for relations with a single target (e.g. BelongsTo, HasOne). This property is needed by OpenAPI/JSON Schema generator.
property type
type: RelationType;
The type of the relation, must be one of RelationType values.
interface Repository
interface Repository<T extends Model> {}
interface RepositoryComponent
interface RepositoryComponent {}
This interface describes additional Component properties allowing components to contribute Repository-related artifacts.
property models
models?: Class<Model>[];
An optional list of Model classes to bind for dependency injection via
app.model()
API.
property repositories
repositories?: Class<Repository<Model>>[];
An optional list of Repository classes to bind for dependency injection via
app.repository()
API.
interface SchemaMigrationOptions
interface SchemaMigrationOptions extends Options {}
property existingSchema
existingSchema?: 'drop' | 'alter';
When set to 'drop', schema migration will drop existing tables and recreate them from scratch, removing any existing data along the way.
When set to 'alter', schema migration will try to preserve current schema and data, and perform a non-destructive incremental update.
property models
models?: string[];
List of model names to migrate.
By default, all models are migrated.
interface Transaction
interface Transaction {}
Local transaction
interface TransactionalRepository
interface TransactionalRepository<T extends Entity> extends Repository<T> {}
Repository Interface for Repositories that support Transactions
method beginTransaction
beginTransaction: (options?: IsolationLevel | Options) => Promise<Transaction>;
Begin a new Transaction
Parameter options
Options for the operations
Returns
Promise Promise that resolves to a new Transaction object
interface Type
interface Type<T> {}
property name
name: string;
Name of the type
method coerce
coerce: (value: any, options?: Options) => T | null | undefined;
Coerce the value into this type
Parameter value
The value to be coerced
Parameter options
Options for coercion
Returns
Coerced value of this type
method defaultValue
defaultValue: () => T | null | undefined;
Generate the default value for this type
method isCoercible
isCoercible: (value: any, options?: Options) => boolean;
Check if the given value can be coerced into this type
Parameter value
The value to to be coerced
Returns
A flag to indicate if the value can be coerced
method isInstance
isInstance: (value: any) => boolean;
Test if the given value is an instance of this type
Parameter value
The value
method serialize
serialize: (value: T | null | undefined, options?: Options) => any;
Serialize a value into json
Parameter value
The value of this type
Parameter options
Options for serialization
Enums
enum IsolationLevel
enum IsolationLevel { READ_COMMITTED = 'READ COMMITTED', READ_UNCOMMITTED = 'READ UNCOMMITTED', SERIALIZABLE = 'SERIALIZABLE', REPEATABLE_READ = 'REPEATABLE READ',}
Isolation level
member READ_COMMITTED
READ_COMMITTED = 'READ COMMITTED'
member READ_UNCOMMITTED
READ_UNCOMMITTED = 'READ UNCOMMITTED'
member REPEATABLE_READ
REPEATABLE_READ = 'REPEATABLE READ'
member SERIALIZABLE
SERIALIZABLE = 'SERIALIZABLE'
enum RelationType
enum RelationType { belongsTo = 'belongsTo', hasOne = 'hasOne', hasMany = 'hasMany', embedsOne = 'embedsOne', embedsMany = 'embedsMany', referencesOne = 'referencesOne', referencesMany = 'referencesMany',}
member belongsTo
belongsTo = 'belongsTo'
member embedsMany
embedsMany = 'embedsMany'
member embedsOne
embedsOne = 'embedsOne'
member hasMany
hasMany = 'hasMany'
member hasOne
hasOne = 'hasOne'
member referencesMany
referencesMany = 'referencesMany'
member referencesOne
referencesOne = 'referencesOne'
Type Aliases
type Callback
type Callback<T> = (err: Error | string | null | undefined, result?: T) => void;
Type alias for Node.js callback functions
type Command
type Command = string | AnyObject;
Type for a command
type Constructor
type Constructor<T> = Class<T> | ConstructorFunction<T>;
Constructor type - class or function
type DataObject
type DataObject<T extends object> = T | DeepPartial<T>;
Type alias for strongly or weakly typed objects of T
type DeepPartial
type DeepPartial<T> = | Partial<T> | { [P in keyof T]?: DeepPartial<T[P]>; };
An extension of the built-in Partial type which allows partial values in deeply nested properties too.
type DynamicModelCtor
type DynamicModelCtor<BaseCtor extends typeof Model, Props extends object> = { /** Model constructor accepting partial model data. */ new (data?: DataObject<PrototypeOf<BaseCtor> & Props>): PrototypeOf<BaseCtor> & Props;} & BaseCtor;
A type describing a model class created via
defineModelClass
.Assuming template arguments
BaseCtor
andProps
, this type describes a class constructor with the following properties: - a constructor function acceptingDataObject<Props>
as the only argument, this argument is optional - all static fields (properties, methods) fromBaseCtor
are inherited and available as static fields on the dynamic class - all prototype fields fromBaseCtor
prototype are inherited and available as prototype fields on the dynamic class
type EntityData
type EntityData = DataObject<Entity>;
type EntityResolver
type EntityResolver<T extends Entity> = TypeResolver<T, typeof Entity>;
type HasManyThroughRepositoryFactory
type HasManyThroughRepositoryFactory< TargetEntity extends Entity, TargetID, ThroughEntity extends Entity, SourceID> = { (fkValue: SourceID): HasManyThroughRepository< TargetEntity, TargetID, ThroughEntity >; /** * Use `resolver` property to obtain an InclusionResolver for this relation. */ inclusionResolver: InclusionResolver<Entity, TargetEntity>;};
a factory to generate hasManyThrough repository class.
Warning: The hasManyThrough interface is experimental and is subject to change. If backwards-incompatible changes are made, a new major version may not be released.
type InclusionResolver
type InclusionResolver<S extends Entity, T extends Entity> = ( /** * List of source models as returned by the first database query. */ sourceEntities: S[], /** * Inclusion requested by the user (e.g. scope constraints to apply). */ inclusion: InclusionFilter, /** * Generic options object, e.g. carrying the Transaction object. */ options?: Options) => Promise<(T | undefined)[] | (T[] | undefined)[]>;
Returns
An array of resolved values, the items must be ordered in the same way as
sourceEntities
. The resolved value can be one of: -undefined
when no target model(s) were found -Entity
for relations targeting a single model -Entity[]
for relations targeting multiple models
type KeyValueFilter
type KeyValueFilter = { /** * Glob string to use to filter returned keys (i.e. `userid.*`). All * connectors are required to support `*` and `?`. They may also support * additional special characters that are specific to the backing database. */ match: string;};
Filter for keys
type NamedParameters
type NamedParameters = AnyObject;
Named parameters, such as
{x: 1, y: 'a'}
type NonFunction
type NonFunction<T> = T extends Function ? never : T;
type Options
type Options = AnyObject;
Type alias for Node.js options object
type PositionalParameters
type PositionalParameters = any[];
Positional parameters, such as [1, 'a']
type PropertyMap
type PropertyMap = MetadataMap<Partial<PropertyDefinition>>;
type PropertyType
type PropertyType = string | Function | object | Type<any> | TypeResolver<Model>;
type PrototypeOf
type PrototypeOf<Ctor extends Function> = Ctor extends { prototype: infer Proto;} ? Proto : never;
Type helper to infer prototype from a constructor function.
Example:
PrototypeOf<typeof Entity>
is resolved toEntity
.
type RelationDefinitionMap
type RelationDefinitionMap = { [relationName: string]: RelationMetadata;};
A key-value map describing model relations. A relation name is used as the key, a relation definition is the value.
type RelationMetadata
type RelationMetadata = | HasManyDefinition | BelongsToDefinition | HasOneDefinition | ReferencesManyDefinition | RelationDefinitionBase;
A union type describing all possible Relation metadata objects.
type RepositoryDecorator
type RepositoryDecorator = ( target: Object, key?: string, descriptorOrIndex?: TypedPropertyDescriptor<any> | number) => void;
Type definition for decorators returned by
@repository
decorator factory
type StringKeyOf
type StringKeyOf<T> = Extract<keyof T, string>;
type TransactionalEntityRepository
type TransactionalEntityRepository< T extends Entity, ID, Relations extends object = {}> = TransactionalRepository<T> & EntityCrudRepository<T, ID>;
A type for CRUD repositories that are backed by IDs and support Transactions
type TypeResolver
type TypeResolver< Type extends Object, StaticMembers = Function> = () => Class<Type> & StaticMembers;
A type resolver is a function that returns a class representing the type, typically a Model or Entity (e.g. Product).
We use type resolvers to break require() loops when defining relations. The target model (class) is provided via a provider, thus deferring the actual reference to the class itself until later, when both sides of the relation are created as JavaScript classes.
Namespaces
namespace ConnectorInterfaces
namespace ConnectorInterfaces {}
Interfaces adopted by a Connector.
Modifiers
@experimental
enum StrongJoins
const enum StrongJoins { INNER = 'strongInnerJoin', LEFT = 'strongLeftJoin', RIGHT = 'strongRightJoin', FULL = 'strongFullJoin', CARTESIAN = 'strongCartesianJoin',}
Strong query join interfaces adopted by a Connector
Modifiers
@experimental
enum StrongRelation
const enum StrongRelation { BELONGS_TO = 'strongBelongsTo', HAS_ONE = 'strongHasOne', HAS_MANY = 'strongHasMany', HAS_MANY_THROUGH = 'strongHasManyThrough', HAS_AND_BELONGS_TO_MANY = 'strongHasAndBelongsToMany', EMBEDS_ONE = 'strongEmbedsOne', EMBEDS_MANY = 'strongEmbedsMany', REFERNCES_MANY = 'strongReferencesMany',}
Strong relation interfaces adopted by a Connector
Modifiers
@experimental
member BELONGS_TO
BELONGS_TO = 'strongBelongsTo'
member EMBEDS_MANY
EMBEDS_MANY = 'strongEmbedsMany'
member EMBEDS_ONE
EMBEDS_ONE = 'strongEmbedsOne'
member HAS_AND_BELONGS_TO_MANY
HAS_AND_BELONGS_TO_MANY = 'strongHasAndBelongsToMany'
member HAS_MANY
HAS_MANY = 'strongHasMany'
member HAS_MANY_THROUGH
HAS_MANY_THROUGH = 'strongHasManyThrough'
member HAS_ONE
HAS_ONE = 'strongHasOne'
member REFERNCES_MANY
REFERNCES_MANY = 'strongReferencesMany'
namespace juggler
namespace juggler {}
namespace property
namespace property {}
variable ERR_NO_ARGS
const ERR_NO_ARGS: string;
variable ERR_PROP_NOT_ARRAY
const ERR_PROP_NOT_ARRAY: string;
function array
array: ( itemType: PropertyType, definition?: Partial<PropertyDefinition>) => (target: object, propertyName: string) => void;
Parameter itemType
The type of array items. Examples:
number
,Product
,() => Order
.Parameter definition
Optional PropertyDefinition object for additional metadata
namespace repository
namespace repository {}
function getter
getter: ( nameOrClass: string | Class<Repository<Model>>) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
Decorator used to inject a Getter for a repository Mainly intended for usage with repository injections on relation repository factory
Parameter nameOrClass
The repository class (ProductRepository) or a string name ('ProductRepository').
namespace RepositoryBindings
namespace RepositoryBindings {}
Binding keys and namespaces for repository related bindings
variable DATASOURCES
const DATASOURCES: string;
Namespace for datasource bindings
variable MODELS
const MODELS: string;
Namespace for model class bindings
variable REPOSITORIES
const REPOSITORIES: string;
Namespace for repository bindings
namespace RepositoryTags
namespace RepositoryTags {}
Binding tags for repository related bindings
variable DATASOURCE
const DATASOURCE: string;
Tag for datasource bindings
variable MODEL
const MODEL: string;
Tag for model class bindings
variable REPOSITORY
const REPOSITORY: string;
Tag for repository bindings
Package Files (59)
- dist/common-types.d.ts
- dist/connectors/connector.d.ts
- dist/connectors/crud.connector.d.ts
- dist/connectors/kv.connector.d.ts
- dist/datasource.d.ts
- dist/decorators/metadata.d.ts
- dist/decorators/model.decorator.d.ts
- dist/decorators/repository.decorator.d.ts
- dist/define-model-class.d.ts
- dist/define-repository-class.d.ts
- dist/errors/entity-not-found.error.d.ts
- dist/errors/invalid-body.error.d.ts
- dist/errors/invalid-polymorphism.error.d.ts
- dist/errors/invalid-relation.error.d.ts
- dist/index.d.ts
- dist/keys.d.ts
- dist/mixins/repository.mixin.d.ts
- dist/model.d.ts
- dist/relations/belongs-to/belongs-to.accessor.d.ts
- dist/relations/belongs-to/belongs-to.decorator.d.ts
- dist/relations/belongs-to/belongs-to.inclusion-resolver.d.ts
- dist/relations/belongs-to/belongs-to.repository.d.ts
- dist/relations/has-many/has-many-through.repository-factory.d.ts
- dist/relations/has-many/has-many-through.repository.d.ts
- dist/relations/has-many/has-many.decorator.d.ts
- dist/relations/has-many/has-many.inclusion-resolver.d.ts
- dist/relations/has-many/has-many.repository-factory.d.ts
- dist/relations/has-many/has-many.repository.d.ts
- dist/relations/has-one/has-one.decorator.d.ts
- dist/relations/has-one/has-one.repository-factory.d.ts
- dist/relations/has-one/has-one.repository.d.ts
- dist/relations/references-many/references-many.accessor.d.ts
- dist/relations/references-many/references-many.decorator.d.ts
- dist/relations/references-many/references-many.inclusion-resolver.d.ts
- dist/relations/references-many/references-many.repository.d.ts
- dist/relations/relation.decorator.d.ts
- dist/relations/relation.filter.solver.d.ts
- dist/relations/relation.helpers.d.ts
- dist/relations/relation.types.d.ts
- dist/repositories/constraint-utils.d.ts
- dist/repositories/kv.repository.bridge.d.ts
- dist/repositories/kv.repository.d.ts
- dist/repositories/legacy-juggler-bridge.d.ts
- dist/repositories/repository.d.ts
- dist/transaction.d.ts
- dist/type-resolver.d.ts
- dist/types/any.d.ts
- dist/types/array.d.ts
- dist/types/boolean.d.ts
- dist/types/buffer.d.ts
- dist/types/date.d.ts
- dist/types/index.d.ts
- dist/types/model.d.ts
- dist/types/null.d.ts
- dist/types/number.d.ts
- dist/types/object.d.ts
- dist/types/string.d.ts
- dist/types/type.d.ts
- dist/types/union.d.ts
Dependencies (6)
Dev Dependencies (8)
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@loopback/repository
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@loopback/repository)
- HTML<a href="https://www.jsdocs.io/package/@loopback/repository"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10391 ms. - Missing or incorrect documentation? Open an issue for this package.