LoopBack 4 Todo Application Tutorial - Add a Repository

Repositories

The repository pattern is one of the more fundamental differences betweenLoopBack 3 and 4. In LoopBack 3, you would use the model class definitionsthemselves to perform CRUD operations. In LoopBack 4, the layer responsible forthis has been separated from the definition of the model itself, into therepository layer.

A Repository represents a specialized Service interface that providesstrong-typed data access (for example, CRUD) operations of a domain modelagainst the underlying database or service.

For more information about Repositories, seeRepositories.

Create your repository

From inside the project folder, run the lb4 repository command to create arepository for your to-do model using the db datasource from the previousstep. The db datasource shows up by its class name DbDataSource from thelist of available datasources.

  1. lb4 repository
  2. ? Please select the datasource DbDatasource
  3. ? Select the model(s) you want to generate a repository Todo
  4. create src/repositories/todo.repository.ts
  5. update src/repositories/index.ts
  6. ? Please select the repository base class DefaultCrudRepository (Legacy juggler
  7. bridge)
  8. Repository TodoRepository was created in src/repositories/

The src/repositories/index.ts file makes exporting artifacts central and alsoeasier to import.

The newly created todo.repository.ts class has the necessary connections thatare needed to perform CRUD operations for our to-do model. It leverages the Todomodel definition and ‘db’ datasource configuration and retrieves the datasourceusingDependency Injection.

Now we can expose the Todo API through thecontroller.

Navigation

Previous step: Add a datasource

Next step: Add a controller