Datasources
Datasources are LoopBack’s way of connecting to various sources of data, such as
databases, APIs, message queues and more. A DataSource
in LoopBack 4 is a
named configuration for a Connector instance that represents data in an external
system. The Connector is used by legacy-juggler-bridge
to power LoopBack 4
Repositories for Data operations.
In LoopBack 4, datasources can be represented as strongly-typed objects and freely made available for injection throughout the application. Typically, in LoopBack 4, datasources are used in conjunction with Repositories to provide access to data.
For more information about datasources in LoopBack, see DataSources.
Since our Todo API will need to persist instances of Todo items, we’ll need to create a datasource definition to make this possible.
Building a Datasource
From inside the project folder, we’ll run the lb4 datasource
command to create
a DataSource. For the purposes of this tutorial, we’ll be using the memory
connector provided with the Juggler.
lb4 datasource
? Datasource name: db
? Select the connector for db: In-memory db (supported by StrongLoop)
? window.localStorage key to use for persistence (browser only):
? Full path to file for persistence (server only): ./data/db.json
create src/datasources/db.datasource.json
create src/datasources/db.datasource.ts
update src/datasources/index.ts
Datasource db was created in src/datasources/
Create a data
folder in the applications root and add a new file called
db.json
contain and example database.
data/db.json
{
"ids": {
"Todo": 5
},
"models": {
"Todo": {
"1": "{\"title\":\"Take over the galaxy\",\"desc\":\"MWAHAHAHAHAHAHAHAHAHAHAHAHAMWAHAHAHAHAHAHAHAHAHAHAHAHA\",\"id\":1}",
"2": "{\"title\":\"destroy alderaan\",\"desc\":\"Make sure there are no survivors left!\",\"id\":2}",
"3": "{\"title\":\"terrorize senate\",\"desc\":\"Tell them they're getting a budget cut.\",\"id\":3}",
"4": "{\"title\":\"crush rebel scum\",\"desc\":\"Every.Last.One.\",\"id\":4}"
}
}
}
Once you’re ready, we’ll move onto adding a repository for the datasource.
Navigation
Previous step: Add your Todo model
Next step: Add a repository