Repository - Data Access Layer

Repository is the layer which contains all data access code. It should abstract all data sources, provides pure Javascript API for other layers to access data in the same way, without care about what the data source is.

To implement a repository, you should follow these rules:

  • One repository for one data source
  • Repository should be a class, with only one instance.
  • Repository should contains only methods to access data.
  • All repositories for HTTP requests must implement Repository class
  • All HTTP method should return an Observable of RxJS
  • Call HTTP API carefully, handle all errors that may occurs, unsubscribe API calls on component unmount events.
  • Each repository should be placed in one file separately.
  • Each repository should export a singleton instance to use outside of where it is implemented.
  • Repository implementations should respect OOP principles

Repository use axios for HTTP requests. To archieve some advanced features (pipeling, unsubscription, …), we fork and maintain our own package from axios-observable, named it @react3l/axios-observable

Example of HTTP Repository:

import { Repository } from "@react3l/react3l/core";
// Export class definition
export class ExampleRepository extends Repository {
  constructor() {
    super({}); // Call super with AxiosRequestConfig
    this.baseURL = "https://example.com/api";
  }

  public sampleAPI = (data: SampleData): Observable<SampleResponse> => {
    return this.httpObservable<SampleResponse>("/sample-data", data).pipe(
      map((response: AxiosResponse<SampleResponse>) => {
        return response.data;
      })
    );
  };
}
// Export a singleton instance
export const exampleRepository: ExampleRepository = new ExampleRepository();