Skip to content

loopback4-sequelize / SequelizeCrudRepository

Class: SequelizeCrudRepository<T, ID, Relations>

Sequelize implementation of CRUD repository to be used with default loopback entities and SequelizeDataSource for SQL Databases

Type parameters

Name Type
T extends Entity
ID ID
Relations extends object = {}

Implements

  • EntityCrudRepository<T, ID, Relations>

Table of contents

Constructors

Properties

Methods

Constructors

constructor

new SequelizeCrudRepository<T, ID, Relations>(entityClass, dataSource)

Type parameters

Name Type
T extends Entity<T>
ID ID
Relations extends object = {}

Parameters

Name Type
entityClass typeof Entity & { prototype: T }
dataSource SequelizeDataSource

Defined in

src/sequelize/sequelize.repository.base.ts:77

Properties

DB_SPECIFIC_SETTINGS_KEYS

Readonly DB_SPECIFIC_SETTINGS_KEYS: readonly ["postgresql", "mysql", "sqlite3"]

Object keys used in models for set database specific settings. Example: In model property definition one can use postgresql dataType as float { type: 'number', postgresql: { dataType: 'float', precision: 20, scale: 4, }, }

This array of keys is used while building model definition for sequelize.

Defined in

src/sequelize/sequelize.repository.base.ts:107


DEFAULT_ORDER_STYLE

Readonly DEFAULT_ORDER_STYLE: "ASC"

Default order filter style if only column name is specified

Defined in

src/sequelize/sequelize.repository.base.ts:91


NANO_ID_LENGTH

NANO_ID_LENGTH: number = 9

Length of the nanoid generated for defaultFn's shortid and nanoid aliases.

Defined in

src/sequelize/sequelize.repository.base.ts:116


dataSource

dataSource: SequelizeDataSource

Defined in

src/sequelize/sequelize.repository.base.ts:81


defaultFnRegistry

Protected defaultFnRegistry: Record<string, () => string | number>

The alias registry for defaultFn option used in model property definition.

See: https://loopback.io/doc/en/lb4/Model.html#property-decorator

Defined in

src/sequelize/sequelize.repository.base.ts:123


entityClass

entityClass: typeof Entity & { prototype: T }

Implementation of

EntityCrudRepository.entityClass

Defined in

src/sequelize/sequelize.repository.base.ts:78


inclusionResolvers

Readonly inclusionResolvers: Map<string, InclusionResolver<T, Entity>>

Implementation of

EntityCrudRepository.inclusionResolvers

Defined in

src/sequelize/sequelize.repository.base.ts:136


sequelizeModel

sequelizeModel: ModelStatic<Model<T, T>>

Sequelize Model Instance created from the model definition received from the entityClass

Defined in

src/sequelize/sequelize.repository.base.ts:144

Methods

beginTransaction

beginTransaction(options?): Promise<Transaction>

Parameters

Name Type
options? TransactionOptions | ISOLATION_LEVELS

Returns

Promise<Transaction>

Defined in

src/sequelize/sequelize.repository.base.ts:1366


buildSequelizeAttributeFilter

Protected buildSequelizeAttributeFilter(fields?): undefined | FindAttributeOptions

Get Sequelize attributes filter value from fields of loopback.

Parameters

Name Type Description
fields? Fields<AnyObject> Loopback styles fields options. eg. ["name", "age"], { id: false }

Returns

undefined | FindAttributeOptions

Sequelize Compatible Object/Array based on the fields provided. eg. { "exclude": ["id"] }

Defined in

src/sequelize/sequelize.repository.base.ts:416


buildSequelizeIncludeFilter

Protected buildSequelizeIncludeFilter(inclusionFilters?, sourceModel?): Includeable[]

Build Sequelize compatible include filter

Parameters

Name Type Description
inclusionFilters? Object[] loopback style where condition
sourceModel? ModelStatic<Model<T, T>> sequelize model instance

Returns

Includeable[]

Sequelize compatible Includeable array

Defined in

src/sequelize/sequelize.repository.base.ts:505


buildSequelizeOrder

Protected buildSequelizeOrder(order?): undefined | Order

Get Sequelize Order filter value from loopback style order value

Parameters

Name Type Description
order? string | string[] Sorting order in loopback style filter. eg. title ASC, ["id DESC", "age ASC"]

Returns

undefined | Order

Sequelize compatible order filter value

Defined in

src/sequelize/sequelize.repository.base.ts:467


buildSequelizeWhere

Protected buildSequelizeWhere<MT>(where?): WhereOptions<MT>

Build Sequelize compatible where condition object

Type parameters

Name Type
MT extends Entity<MT>

Parameters

Name Type Description
where? Where<MT> loopback style where condition

Returns

WhereOptions<MT>

Sequelize compatible where options to be used in queries

Defined in

src/sequelize/sequelize.repository.base.ts:602


count

count(where?, options?): Promise<Count>

Parameters

Name Type
where? Where<T>
options? AnyObject

Returns

Promise<Count>

Implementation of

EntityCrudRepository.count

Defined in

src/sequelize/sequelize.repository.base.ts:348


create

create(entity, options?): Promise<T>

Parameters

Name Type
entity DataObject<T>
options? AnyObject

Returns

Promise<T>

Implementation of

EntityCrudRepository.create

Defined in

src/sequelize/sequelize.repository.base.ts:146


createAll

createAll(entities, options?): Promise<T[]>

Parameters

Name Type
entities DataObject<T>[]
options? AnyObject

Returns

Promise<T[]>

Implementation of

EntityCrudRepository.createAll

Defined in

src/sequelize/sequelize.repository.base.ts:154


createBelongsToAccessorFor

Protected createBelongsToAccessorFor<Target, TargetId>(relationName, targetRepositoryGetter): BelongsToAccessor<Target, ID>

Function to create a belongs to accessor

Type parameters

Name Type
Target extends Entity<Target>
TargetId TargetId

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
targetRepositoryGetter Getter<EntityCrudRepository<Target, TargetId, {}>> | { [repoType: string]: Getter<EntityCrudRepository<Target, TargetId>>; } -

Returns

BelongsToAccessor<Target, ID>

Defined in

src/sequelize/sequelize.repository.base.ts:1243


createHasManyRepositoryFactoryFor

Protected createHasManyRepositoryFactoryFor<Target, TargetID, ForeignKeyType>(relationName, targetRepositoryGetter): HasManyRepositoryFactory<Target, ForeignKeyType>

Function to create a constrained relation repository factory

Example

class CustomerRepository extends SequelizeCrudRepository<
  Customer,
  typeof Customer.prototype.id,
  CustomerRelations
> {
  public readonly orders: HasManyRepositoryFactory<Order, typeof Customer.prototype.id>;

  constructor(
    protected db: SequelizeDataSource,
    orderRepository: EntityCrudRepository<Order, typeof Order.prototype.id>,
  ) {
    super(Customer, db);
    this.orders = this.createHasManyRepositoryFactoryFor(
      'orders',
      orderRepository,
    );
  }
}

Type parameters

Name Type
Target extends Entity<Target>
TargetID TargetID
ForeignKeyType ForeignKeyType

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
targetRepositoryGetter Getter<EntityCrudRepository<Target, TargetID, {}>> -

Returns

HasManyRepositoryFactory<Target, ForeignKeyType>

Defined in

src/sequelize/sequelize.repository.base.ts:1222


createHasManyThroughRepositoryFactoryFor

Protected createHasManyThroughRepositoryFactoryFor<Target, TargetID, Through, ThroughID, ForeignKeyType>(relationName, targetRepositoryGetter, throughRepositoryGetter): HasManyThroughRepositoryFactory<Target, TargetID, Through, ForeignKeyType>

Function to create a constrained hasManyThrough relation repository factory

Example

class CustomerRepository extends SequelizeCrudRepository<
  Customer,
  typeof Customer.prototype.id,
  CustomerRelations
> {
  public readonly cartItems: HasManyRepositoryFactory<CartItem, typeof Customer.prototype.id>;

  constructor(
    protected db: SequelizeDataSource,
    cartItemRepository: EntityCrudRepository<CartItem, typeof, CartItem.prototype.id>,
    throughRepository: EntityCrudRepository<Through, typeof Through.prototype.id>,
  ) {
    super(Customer, db);
    this.cartItems = this.createHasManyThroughRepositoryFactoryFor(
      'cartItems',
      cartItemRepository,
    );
  }
}

Type parameters

Name Type
Target extends Entity<Target>
TargetID TargetID
Through extends Entity<Through>
ThroughID ThroughID
ForeignKeyType ForeignKeyType

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
targetRepositoryGetter Getter<EntityCrudRepository<Target, TargetID, {}>> | { [repoType: string]: Getter<EntityCrudRepository<Target, TargetID>>; } -
throughRepositoryGetter Getter<EntityCrudRepository<Through, ThroughID, {}>> -

Returns

HasManyThroughRepositoryFactory<Target, TargetID, Through, ForeignKeyType>

Defined in

src/sequelize/sequelize.repository.base.ts:1314


createHasOneRepositoryFactoryFor

Protected createHasOneRepositoryFactoryFor<Target, TargetID, ForeignKeyType>(relationName, targetRepositoryGetter): HasOneRepositoryFactory<Target, ForeignKeyType>

Function to create a constrained hasOne relation repository factory

Type parameters

Name Type
Target extends Entity<Target>
TargetID TargetID
ForeignKeyType ForeignKeyType

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
targetRepositoryGetter Getter<EntityCrudRepository<Target, TargetID, {}>> | { [repoType: string]: Getter<EntityCrudRepository<Target, TargetID>>; } -

Returns

HasOneRepositoryFactory<Target, ForeignKeyType>

Defined in

src/sequelize/sequelize.repository.base.ts:1265


createReferencesManyAccessorFor

Protected createReferencesManyAccessorFor<Target, TargetId>(relationName, targetRepoGetter): ReferencesManyAccessor<Target, ID>

Function to create a references many accessor

Type parameters

Name Type
Target extends Entity<Target>
TargetId TargetId

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
targetRepoGetter Getter<EntityCrudRepository<Target, TargetId, {}>> -

Returns

ReferencesManyAccessor<Target, ID>

Defined in

src/sequelize/sequelize.repository.base.ts:1354


delete

delete(entity, options?): Promise<void>

Parameters

Name Type
entity T
options? AnyObject

Returns

Promise<void>

Implementation of

EntityCrudRepository.delete

Defined in

src/sequelize/sequelize.repository.base.ts:225


deleteAll

deleteAll(where?, options?): Promise<Count>

Parameters

Name Type
where? Where<T>
options? AnyObject

Returns

Promise<Count>

Implementation of

EntityCrudRepository.deleteAll

Defined in

src/sequelize/sequelize.repository.base.ts:318


deleteById

deleteById(id, options?): Promise<void>

Parameters

Name Type
id ID
options? AnyObject

Returns

Promise<void>

Implementation of

EntityCrudRepository.deleteById

Defined in

src/sequelize/sequelize.repository.base.ts:329


excludeHiddenProps

Protected excludeHiddenProps(entity): T & Relations

Remove hidden properties specified in model from response body. (See: https://github.com/sourcefuse/loopback4-sequelize/issues/3)

Deprecated

To exclude hidden props from a model call the .toJSON() method on it Which is available for models returned from create, find or findById method. Alternative it can be use by manually instantiating the model using new EntityClass(data).toJSON().

This function will be removed in next major release.

Parameters

Name Type Description
entity T & Relations normalized entity. You can use entity.toJSON()'s value

Returns

T & Relations

normalized entity excluding the hiddenProperties

Defined in

src/sequelize/sequelize.repository.base.ts:945


execute

execute(command, parameters?, options?): 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.

Example

// MySQL
const result = await repo.execute(
  'SELECT * FROM Products WHERE size > ?',
  [42]
);

// PostgreSQL
const result = await repo.execute(
  'SELECT * FROM Products WHERE size > $1',
  [42]
);

Parameters

Name Type Description
command Command A parameterized SQL command or query.
parameters? AnyObject | PositionalParameters List of parameter values to use.
options? AnyObject Additional options, for example transaction.

Returns

Promise<AnyObject>

A promise which resolves to the command output. The output type (data structure) is database specific and often depends on the command executed.

Implementation of

EntityCrudRepository.execute

Defined in

src/sequelize/sequelize.repository.base.ts:386


exists

exists(id, _options?): Promise<boolean>

Parameters

Name Type
id ID
_options? AnyObject

Returns

Promise<boolean>

Implementation of

EntityCrudRepository.exists

Defined in

src/sequelize/sequelize.repository.base.ts:166


find

find(filter?, options?): Promise<T & Relations[]>

Parameters

Name Type
filter? Filter<T>
options? AnyObject

Returns

Promise<T & Relations[]>

Implementation of

EntityCrudRepository.find

Defined in

src/sequelize/sequelize.repository.base.ts:229


findById

findById(id, filter?, options?): Promise<T & Relations>

Parameters

Name Type
id ID
filter? FilterExcludingWhere<T>
options? AnyObject

Returns

Promise<T & Relations>

Implementation of

EntityCrudRepository.findById

Defined in

src/sequelize/sequelize.repository.base.ts:276


findOne

findOne(filter?, options?): Promise<null | T & Relations>

Parameters

Name Type
filter? Filter<T>
options? AnyObject

Returns

Promise<null | T & Relations>

Defined in

src/sequelize/sequelize.repository.base.ts:250


getDefaultFnRegistry

Protected getDefaultFnRegistry(): Record<string, () => string | number>

Returns

Record<string, () => string | number>

Defined in

src/sequelize/sequelize.repository.base.ts:132


getSequelizeModel

getSequelizeModel(entityClass?): ModelCtor<Model<any, any>> | ModelCtor<SequelizeModel>

Get Sequelize Model

Parameters

Name Type
entityClass typeof Entity & { prototype: T }

Returns

ModelCtor<Model<any, any>> | ModelCtor<SequelizeModel>

Sequelize Model Instance based on the definitions from entityClass

Defined in

src/sequelize/sequelize.repository.base.ts:661


getSequelizeModelAttributes

Protected getSequelizeModelAttributes(definition): ModelAttributes<SequelizeModel, any>

Get Sequelize Model Attributes

Parameters

Name Type Description
definition Object property definition received from loopback entityClass eg. { id: { type: "Number", id: true } }

Returns

ModelAttributes<SequelizeModel, any>

model attributes supported in sequelize model definiotion

TODO: Verify all possible loopback types https://loopback.io/doc/en/lb4/LoopBack-types.html

Defined in

src/sequelize/sequelize.repository.base.ts:815


getSequelizeOperator

Protected getSequelizeOperator(key): symbol

Get Sequelize Operator

Parameters

Name Type Description
key Operators Name of the operator used in loopback eg. lt

Returns

symbol

Equivalent operator symbol if available in Sequelize eg Op.lt

Defined in

src/sequelize/sequelize.repository.base.ts:403


getTableName

getTableName(entityClass?): string

This function retrieves the table name associated with a given entity class. Different loopback connectors have different conventions for picking up table names, unless the name is specified in the

Model

decorator.

The function follows the following cases to determine the table name: - It checks if the name property is specified in the

Model

decorator and uses it. (this takes precedence over all other cases) - If the dialect of the dataSource is PostgreSQL, it uses the lowercased version of the model class name. - If the dialect is MySQL or any other dialect, it uses the default model class name.

Parameters

Name Type Description
entityClass typeof Entity & { prototype: T } The entity class for which the table name is being retrieved.

Returns

string

  • The table name associated with the entity class. Which is used when performing the query.

Defined in

src/sequelize/sequelize.repository.base.ts:771


includeReferencesIfRequested

Protected includeReferencesIfRequested(parentEntities, parentEntityClass, inclusionFilters?): Promise<T & Relations[]>

Include related entities of @referencesMany relation

referencesMany relation is NOT handled by sequelizeModel.findAll as it doesn't have any direct alternative to it, so to include relation data of referencesMany, we're manually fetching related data requested

Parameters

Name Type Description
parentEntities Model<T, T>[] source table data
parentEntityClass typeof Entity loopback entity class for the parent entity
inclusionFilters? InclusionFilter[] -

Returns

Promise<T & Relations[]>

entities with related models in them

Defined in

src/sequelize/sequelize.repository.base.ts:969


isInclusionAllowed

Protected isInclusionAllowed(include): boolean

Checks if the resolver of the inclusion relation is registered in the inclusionResolver of the current repository

Parameters

Name Type Description
include InclusionFilter LoopBack Inclusion filter

Returns

boolean

Defined in

src/sequelize/sequelize.repository.base.ts:489


registerInclusionResolver

registerInclusionResolver(relationName, resolver): void

Register an inclusion resolver for the related model name.

Parameters

Name Type Description
relationName string Name of the relation defined on the source model
resolver InclusionResolver<T, Entity> Resolver function for getting related model entities

Returns

void

Defined in

src/sequelize/sequelize.repository.base.ts:1187


replaceById

replaceById(id, data, options?): Promise<void>

Parameters

Name Type
id ID
data DataObject<T>
options? AnyObject

Returns

Promise<void>

Implementation of

EntityCrudRepository.replaceById

Defined in

src/sequelize/sequelize.repository.base.ts:305


save

save(entity, options?): Promise<T>

Parameters

Name Type
entity T
options? AnyObject

Returns

Promise<T>

Implementation of

EntityCrudRepository.save

Defined in

src/sequelize/sequelize.repository.base.ts:179


syncLoadedSequelizeModels

syncLoadedSequelizeModels(options?): Promise<void>

Run CREATE TABLE query for the all sequelize models, Useful for quick testing

Parameters

Name Type Description
options SyncOptions Sequelize Sync Options

Returns

Promise<void>

Defined in

src/sequelize/sequelize.repository.base.ts:804


syncSequelizeModel

syncSequelizeModel(options?): Promise<void>

Run CREATE TABLE query for the target sequelize model, Useful for quick testing

Parameters

Name Type Description
options SyncOptions Sequelize Sync Options

Returns

Promise<void>

Defined in

src/sequelize/sequelize.repository.base.ts:789


toEntities

Protected toEntities(models): T[]

Parameters

Name Type
models Model<T, T>[]

Returns

T[]

Defined in

src/sequelize/sequelize.repository.base.ts:394


update

update(entity, options?): Promise<void>

Parameters

Name Type
entity T
options? AnyObject

Returns

Promise<void>

Implementation of

EntityCrudRepository.update

Defined in

src/sequelize/sequelize.repository.base.ts:189


updateAll

updateAll(data, where?, options?): Promise<Count>

Parameters

Name Type
data DataObject<T>
where? Where<T>
options? AnyObject

Returns

Promise<Count>

Implementation of

EntityCrudRepository.updateAll

Defined in

src/sequelize/sequelize.repository.base.ts:210


updateById

updateById(id, data, options?): Promise<void>

Parameters

Name Type
id ID
data DataObject<T>
options? AnyObject

Returns

Promise<void>

Implementation of

EntityCrudRepository.updateById

Defined in

src/sequelize/sequelize.repository.base.ts:193