Page Contents

Repositories can be created at runtime using the defineCrudRepositoryClass helper function from the @loopback/rest-crud package. It creates DefaultCrudRepository-based repository classes by default.

const BookRepository = defineCrudRepositoryClass<

In case you want to use a non-DefaultCrudRepository repository class or you want to create a custom repository, use the defineRepositoryClass() helper function instead. Pass a second parameter to this function as the base class for the new repository.

There are two options for doing this:

1. Using a base repository class

Create a base repository with your custom implementation, and then specify this repository as the base class.

class MyRepoBase<
  E extends Entity,
  Relations extends object
> extends DefaultCrudRepository<E, IdType, Relations> {
  // Custom implementation

const BookRepositoryClass = defineRepositoryClass<
  typeof BookModel,
  MyRepoBase<BookModel, typeof, BookRelations>
>(BookModel, MyRepoBase);

2. Using a Repository mixin

Create a repository mixin with your customization as shown in the Defining A Repository Mixin Class Factory Function example, apply the mixin on the base repository class (e.g. DefaultCrudRepository) then specify this combined repository as the base class to be used.

const BookRepositoryClass = defineRepositoryClass<
  typeof BookModel,
  > &
>(BookModel, FindByTitleRepositoryMixin(DefaultCrudRepository));

Dependency injection has to be configured for the datasource as shown below.

inject(`datasources.${}`)(BookRepository, undefined, 0);
const repoBinding = app.repository(BookRepository);