loopbackv4l2loopback

Loopback 4 What is a Repository?


I am having a hard time understanding the concept of Repositories in Loopback 4 the documentation says:

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

but this description doesn't help me fully grasp the idea behind them, Can someone explain in simple terms what it is exactly and provide some examples of similar concepts in other frameworks?


Solution

  • When using an ORM (Object Relational Mapper) framework, we represent data as model classes:

    @model()
    class Person {
      @property()
      name: string;
    }
    

    To persist and query the data, we need to add behavior to our models. Repositories are classes providing such behavior.

    For example, LoopBack's EntityCrudRepository interface describes methods for creating, updating, deleting and querying data in SQL tables/NoSQL document collections.

    // simplified version
    interface EntityCrudRepository<T, ID> {
      create(data: DataObject<T>): Promise<T>;
      find(filter?: Filter<T>): Promise<T[]>;
      updateById(id: ID, data: DataObject<T>): Promise<void>;
      deleteById(id: ID): Promise<void>;
      // etc.
    }
    

    The KeyValueRepository describes API for working with key-value storage like Redis:

    interface KeyValueRepository<T> {
      get(key: string): Promise<T>;
      set(key: string, value: DataObject<T>): Promise<void>;
      delete(key: string): Promise<void>;
    }
    

    See also Patterns of Enterprise Application Architecture:

    Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.