Overview

A DataSource in LoopBack 4 is a named configuration for a Connector instancethat represents data in an external system. The Connector is used bylegacy-juggler-bridge to power LoopBack 4 Repositories for Data operations.

Datasource diagram

Creating a DataSource

It is recommended to use the lb4 datasource commandprovided by the CLI to generate a DataSource. The CLI will prompt for allnecessary connector information and create the following files:

  • ${dataSource.dataSourceName}.datasource.json containing the connectorconfiguration
  • ${dataSource.dataSourceName}.datasource.ts containing a class extendingjuggler.DataSource. This class can be used to override the defaultDataSource behaviour programaticaly. Note: The connector configuration storedin the .json file is injected into this class usingDependency Injection.Both the above files are generated in src/datasources/ directory by the CLI.It will also update src/datasources/index.ts to export the new DataSourceclass.

Example DataSource Class:

  1. import {inject} from '@loopback/core';
  2. import {juggler} from '@loopback/repository';
  3. import * as config from './db.datasource.json';
  4. export class DbDataSource extends juggler.DataSource {
  5. static dataSourceName = 'db';
  6. constructor(
  7. @inject('datasources.config.db', {optional: true})
  8. dsConfig: object = config,
  9. ) {
  10. super(dsConfig);
  11. }
  12. }