LoopBack 4 Todo Application Tutorial - Add a Datasource

Datasources

Datasources are LoopBack’s way of connecting to various sources of data, such asdatabases, APIs, message queues and more. A DataSource in LoopBack 4 is anamed configuration for a Connector instance that represents data in an externalsystem. The Connector is used by legacy-juggler-bridge to power LoopBack 4Repositories for Data operations.

In LoopBack 4, datasources can be represented as strongly-typed objects andfreely made available for injection throughout theapplication. Typically, in LoopBack 4, datasources are used in conjunction withRepositories to provide access to data.

For more information about datasources in LoopBack, seeDataSources.

Since our Todo API will need to persist instances of Todo items, we’ll need tocreate a datasource definition to make this possible.

Building a Datasource

From inside the project folder, we’ll run the lb4 datasource command to createa DataSource. For the purposes of this tutorial, we’ll be using the memoryconnector provided with the Juggler.

  1. lb4 datasource
  2. ? Datasource name: db
  3. ? Select the connector for db: In-memory db (supported by StrongLoop)
  4. ? window.localStorage key to use for persistence (browser only):
  5. ? Full path to file for persistence (server only): ./data/db.json
  6. create src/datasources/db.datasource.json
  7. create src/datasources/db.datasource.ts
  8. update src/datasources/index.ts
  9. Datasource Db was created in src/datasources/

Create a data folder in the applications root and add a new file calleddb.json containing an example database.

data/db.json

  1. {
  2. "ids": {
  3. "Todo": 5
  4. },
  5. "models": {
  6. "Todo": {
  7. "1": "{\"title\":\"Take over the galaxy\",\"desc\":\"MWAHAHAHAHAHAHAHAHAHAHAHAHAMWAHAHAHAHAHAHAHAHAHAHAHAHA\",\"id\":1}",
  8. "2": "{\"title\":\"destroy alderaan\",\"desc\":\"Make sure there are no survivors left!\",\"id\":2}",
  9. "3": "{\"title\":\"play space invaders\",\"desc\":\"Become the very best!\",\"id\":3}",
  10. "4": "{\"title\":\"crush rebel scum\",\"desc\":\"Every.Last.One.\",\"id\":4}"
  11. }
  12. }
  13. }

Note:If you are using a relational database as thedatasource, don’t forget to create the corresponding table or follow theDatabase migration instruction to get it created programmatically.

Once you’re ready, we’ll move onto adding arepository for the datasource.

Navigation

Previous step: Add your Todo model

Next step: Add a repository