Page Contents

Home > @loopback/repository

repository package

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.

Classes

Class Description
AnyType Any type
ArrayType Array type, such as string[]
BooleanType Boolean type
BufferType Buffer (binary) type
CrudRepositoryImpl Repository implementation
DateType Date type
DefaultBelongsToRepository  
DefaultCrudRepository Default implementation of CRUD repository using legacy juggler model and data source
DefaultHasManyRepository  
DefaultHasManyThroughRepository 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.
DefaultHasOneRepository  
DefaultKeyValueRepository An implementation of KeyValueRepository based on loopback-datasource-juggler
DefaultTransactionalRepository Default implementation of CRUD repository using legacy juggler model and data source with beginTransaction() method for connectors which support Transactions
Entity Base class for entities which have unique ids
EntityNotFoundError  
Event Domain events
InvalidRelationError  
Model Base class for models
ModelDefinition Definition for a model
ModelMetadataHelper  
ModelType Model type
NullType Null type
NumberType Number type
ObjectType Object type
RepositoryMetadata Metadata for a repository
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
StringType String type
UnionType Union type, such as string | number
ValueObject Base class for value objects - An object that contains attributes but has no conceptual identity. They should be treated as immutable.

Enumerations

Enumeration Description
IsolationLevel Isolation level
RelationType  

Functions

Function Description
belongsTo(targetResolver, definition, propertyDefinition) Decorator for belongsTo
bindModel(modelClass, ds) 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
buildLookupMap(list, keyName, reducer) Returns a map which maps key values(ids) to instances. The instances can be grouped by different strategies.
buildModelDefinition(target, def) Build model definition from decorations
constrainDataObject(originalData, constraint) A utility function which takes a model instance data and enforces constraint(s) on it
constrainDataObjects(originalData, constraint) A utility function which takes an array of model instance data and enforces constraint(s) on it
constrainFilter(originalFilter, constraint) A utility function which takes a filter and enforces constraint(s) on it
constrainWhere(originalWhere, constraint) A utility function which takes a where filter and enforces constraint(s) on it
constrainWhereOr(originalWhere, constraint) A utility function which takes a where filter and enforces constraint(s) on it with OR clause
createBelongsToAccessor(belongsToMetadata, targetRepoGetter, sourceRepository) Enforces a BelongsTo constraint on a repository
createBelongsToInclusionResolver(meta, getTargetRepo) 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
createHasManyInclusionResolver(meta, getTargetRepo) 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.
createHasManyRepositoryFactory(relationMetadata, targetRepositoryGetter) 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).
createHasManyThroughRepositoryFactory(relationMetadata, targetRepositoryGetter, throughRepositoryGetter)  
createHasOneRepositoryFactory(relationMetadata, targetRepositoryGetter) 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).
createModelClassBinding(modelClass) Create a binding for the given model class
deduplicate(input) Dedupe an array
defineCrudRepositoryClass(entityClass) Create (define) an entity CRUD repository class for the given model. This function always uses DefaultCrudRepository as the base class, use defineRepositoryClass if you want to use your own base repository.
defineKeyValueRepositoryClass(modelClass) Create (define) a KeyValue repository class for the given entity. This function always uses DefaultKeyValueRepository as the base class, use defineRepositoryClass if you want to use your own base repository.
defineModelClass(base, definition) Create (define) a new model class with the given name and definition.
defineRepositoryClass(modelClass, baseRepositoryClass) Create (define) a repository class for the given model.See also defineCrudRepositoryClass and defineKeyValueRepositoryClass 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 and R from the class constructors provided in function arguments. You must always provide both M and R types explicitly.**
embedsMany(definition) Decorator for embedsMany
embedsOne(definition) Decorator for embedsOne
ensurePromise(p) Ensure the value is a promise
findByForeignKeys(targetRepository, fkName, fkValues, scope, options) Finds model instances that contain any of the provided foreign key values.
flattenMapByKeys(sourceIds, targetMap) Returns an array of instances from the target map. The order of arrays is based on the order of sourceIds
flattenTargetsOfOneToManyRelation(sourceIds, targetEntities, targetKey) 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
flattenTargetsOfOneToOneRelation(sourceIds, targetEntities, targetKey) Returns an array of instances. The order of arrays is based on the order of sourceIds
getKeyValue(model, keyName) Returns value of a keyName. Aims to resolve ObjectId problem of Mongo.
getModelRelations(modelCtor) Get metadata of all relations defined on a given model class.
hasMany(targetResolver, definition) Decorator for hasMany Calls property.array decorator underneath the hood and infers foreign key name from target model name unless explicitly specified
hasOne(targetResolver, definition)  
includeRelatedModels(targetRepository, entities, include, options) Returns model instances that include related models that have a registered resolver.
isBsonType(value) 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.
isBuiltinType(fn) Check if the provided function is a built-in type provided by JavaScript and/or Node.js. E.g. Number, Array, Buffer, etc.
isEntityNotFoundError(e)  
isInvalidRelationError(e)  
isTypeResolver(fn) A function that checks whether a function is a TypeResolver or not.
model(definition) Decorator for model definitions
normalizeKey(rawKey) Workaround for MongoDB, where the connector returns ObjectID values even for properties configured with “type: string”.
Null() A boxed type for null
property(definition) Decorator for model properties
reduceAsArray(acc, it) Returns an array of instances. For HasMany relation usage.
reduceAsSingleItem(_acc, it) Returns a single of an instance. For HasOne and BelongsTo relation usage.
referencesMany(definition) Decorator for referencesMany
referencesOne(definition) Decorator for referencesOne
rejectNavigationalPropertiesInData(modelClass, data) Check model data for navigational properties linking to related models. Throw a descriptive error if any such property is found.
relation(definition) Decorator for relations
repository(repositoryName) Decorator for repository injections on properties or method arguments
repository(model, dataSource) Decorator for DefaultCrudRepository generation and injection on properties or method arguments based on the given model and dataSource (or their names)
RepositoryMixin(superClass) 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.
resolveType(fn) Resolve a type value that may have been provided via TypeResolver.
resolveType(fn)  

Interfaces

Interface Description
AnyObject Objects with open properties
ApplicationWithRepositories Interface for an Application mixed in with RepositoryMixin
BaseRepositoryClass 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.
BelongsToAccessor  
BelongsToDefinition  
BelongsToRepository CRUD operations for a target repository of a BelongsTo relation
Class Interface for classes with new operator and static properties/methods
Connector Common properties/operations for connectors
ConstructorFunction Interface for constructor functions without new operator.
Count Count of Model instances that were successful for methods like updateAll, deleteAll, etc.
CrudConnector CRUD operations for connector implementations
CrudRepository Basic CRUD operations for ValueObject and Entity. No ID is required.
DataSource DataSource denotes a configured connector
EntityCrudRepository CRUD operations for a repository of entities
EntityRepository Base interface for a repository of entities
ExecutableRepository  
HasManyDefinition HasManyDefinition defines one-to-many relations and also possible defines many-to-many relations with through models.
HasManyRepository CRUD operations for a target repository of a HasMany relation
HasManyRepositoryFactory  
HasManyThroughRepository CRUD operations for a target repository of a HasManyThrough relationEXPERIMENTAL: This interface is not stable and may change in the near future. Backwards-incompatible changes may be introduced in semver-minor versions.
HasOneDefinition  
HasOneRepository CRUD operations for a target repository of a HasMany relation
HasOneRepositoryFactory  
JsonSchemaWithExtensions This module defines the key classes representing building blocks for Domain Driven Design. See https://en.wikipedia.org/wiki/Domain-driven_design#Building_blocks
KeyValueRepository Key/Value operations for connector implementations
KVConnector Key/Value operations for connector implementations
ModelDefinitionSyntax DSL for building a model definition.
ModelRepositoryClass 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.
ModelSettings Defining the settings for a model See https://loopback.io/doc/en/lb4/Model.html#supported-entries-of-model-definition
Persistable  
PropertyDefinition Property definition for a model
PropertyForm See https://github.com/loopbackio/loopback-datasource-juggler/issues/432
RelationDefinitionBase  
Repository  
RepositoryComponent This interface describes additional Component properties allowing components to contribute Repository-related artifacts.
SchemaMigrationOptions  
Transaction Local transaction
TransactionalRepository Repository Interface for Repositories that support Transactions
Type  

Namespaces

Namespace Description
ConnectorInterfaces Interfaces adopted by a Connector.
juggler  
property  
repository  
RepositoryBindings Binding keys and namespaces for repository related bindings
RepositoryTags Binding tags for repository related bindings

Variables

Variable Description
ANY  
BOOLEAN  
BUFFER  
CountSchema JSON Schema describing the Count interface. It’s the response type for REST calls to APIs which return count. The type is compatible with SchemaObject from @loopback/openapi-v3, which is not an explicit dependency for @loopback/repository.
DATE  
MODEL_KEY  
MODEL_PROPERTIES_KEY  
MODEL_WITH_PROPERTIES_KEY  
NULL  
NUMBER  
RELATIONS_KEY  
STRING  

Type Aliases

Type Alias Description
Callback Type alias for Node.js callback functions
Command Type for a command
Constructor Constructor type - class or function
DataObject Type alias for strongly or weakly typed objects of T
DeepPartial An extension of the built-in Partial type which allows partial values in deeply nested properties too.
DynamicModelCtor A type describing a model class created via defineModelClass.Assuming template arguments BaseCtor and Props, this type describes a class constructor with the following properties: - a constructor function accepting DataObject<Props> as the only argument, this argument is optional - all static fields (properties, methods) from BaseCtor are inherited and available as static fields on the dynamic class - all prototype fields from BaseCtor prototype are inherited and available as prototype fields on the dynamic class
EntityData  
EntityResolver  
HasManyThroughRepositoryFactory 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.
InclusionResolver  
KeyValueFilter Filter for keys
NamedParameters Named parameters, such as {x: 1, y: 'a'}
Options Type alias for Node.js options object
PositionalParameters Positional parameters, such as [1, ‘a’]
PropertyMap  
PropertyType  
PrototypeOf Type helper to infer prototype from a constructor function.Example: PrototypeOf<typeof Entity> is resolved to Entity.
RelationDefinitionMap A key-value map describing model relations. A relation name is used as the key, a relation definition is the value.
RelationMetadata A union type describing all possible Relation metadata objects.
RepositoryDecorator Type definition for decorators returned by @repository decorator factory
StringKeyOf  
TransactionalEntityRepository A type for CRUD repositories that are backed by IDs and support Transactions
TypeResolver 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.