There are several use cases for importing data into a loopback data source. I've listed the ones that I can think of, feel free to add any.
- As a developer working on a new project, I need test data to work with. This could be for integration tests, prototyping, or even modeling data.
- As a developer working on an existing project with exsiting data, I need to constantly update my local development data with that which mirrors, closely mirrors, or simulates prodution data.
- LoopBack internals require data to be imported during app startup. Although it is important to note that the core could be modified in a way that does not depend on bootstrapped data.
Here is a basic example of an API and JSON format that could make implementing these use cases fairly straightforward and simple.
var app = loopback();
var db = app.dataSource('db', {connector: loopback.Memory});
var Car = app.model('Car', {dataSource: 'db'});
var Dealership = app.model('Dealership', {dataSource: 'db'});
var Option = app.model('Option', {dataSource: 'db'});
var Make = app.model('Make', {dataSource: 'db'});
Dealership.hasMany(Car);
Car.hasMany(Option);
Make.hasMany(Car);
// data.json
{
data: {
dealerships: [
{
name: 'acme cars',
$cars: [
{model: '500', $make: '#fiat', $options: ['#leather', '#ac']},
{model: 's4', $make: '#audi', $options: '.audi-options'},
{model: 'm3', $make: '#bmw'},
]
}
],
makes: [
{name: 'audi', $$id: 'audi'}
{name: 'fiat', $$id: 'fiat'}
{name: 'bmw', $$id: 'bmw'}
],
options: [
{name: 'leather', $$id: 'leather'},
{name: 'ac', $$id: 'ac'},
{name: 'audi option 1', $$class: 'audi-options'},
{name: 'audi option 2', $$class: 'audi-options'}
]
}
}
var testData = app.createDataSet({
file: 'data.json', //or data: someDataObj
});
testData.import({drop: true}, function (err) {
console.log(err || 'Data imported');
});
A bit of reference for the JSON format:
- $$ - indicates a reference only for use by the importer, allowing references / relations to be created before the actual object is inserted and id generated
- $$id - for referencing a single instance
- $$class - for referencing several instances
- $ - indicates a special property. For now, this is used only for relations
- $myRleationProperty - indicates the value for this key is a string or array of strings referencing classes or ids (see above).
- .my-class-name - similar to how classes work in CSS: allows you to reference a set of objects tagged with a
$$class: 'my-class-name.
- #my-id - similar to how ids work in CSS: allows you to reference a single object by id
There are several use cases for importing data into a loopback data source. I've listed the ones that I can think of, feel free to add any.
Here is a basic example of an API and JSON format that could make implementing these use cases fairly straightforward and simple.
A bit of reference for the JSON format:
$$class: 'my-class-name.