-
Notifications
You must be signed in to change notification settings - Fork 1
Model Definition & Configuration
Model definitions are stored within the configured source folder for models, in our case ./app/models/ (./server/) by default. To create a new model one has to create a .json file (preferably having the same name as the model) in the ./app/models folder. To customize your model programmatically, you can create a .js file with the same name, exporting a customization function (see documentation linked below for more information).
Loopback allows adding custom settings to model and overriding them (without any further restrictions):
Add your configuration to your model definition by adding whatever you want to the corresponding .json file:
{
"name": "Example",
"myConfig": {
"myConfigValue": true
}
}These settings are available on the model
const exampleModel = app.models.Example;
// true
const { myConfigValue } = exampleModel.definition.settings.myConfig;Similar to the model's definition you can add configuration to a property of a model:
{
"name": "Example",
"properties": {
"myProperty": {
"type": "string",
"myPropertyConfig": {
"myPropertyConfigValue": true
}
}
}
}These settings are available on the model
const exampleModel = app.models.Example;
// true
const { myPropertyConfigValue } = exampleModel.definition.properties.myPropertyConfig;Similar to the model's property you can add configuration to a relation of a model.
Note: While the model definition provides an accessor for properties as well as relations, the later do usually seem to be empty (i guess it depends on the attached datasource). Therefore you might want to access their definition as described below.
{
"name": "Example",
"relations": {
"myRelation": {
"type": "belongsTo",
"model": "AnotherModel",
"myRelationConfig": {
"myRelationConfigValue": true
}
}
}
}These settings are available on the model
const exampleModel = app.models.Example;
// true
const { myPropertyConfigValue } = exampleModel.definition.settings.relations.myRelationConfig;One can override the settings given in the model definition in the environment specific model-config.json. This can be used to override settings of a model for different environments and datasources.
{
"Example": {
"dataSource": "memory",
"options": {
"myConfig": {
"myConfigValue": false,
"myAdditionalConfigValue": "yay"
}
}
}
}This will extend the basic settings of the model:
const exampleModel = app.models.Example;
/**
* {
* myConfigValue: false,
* myAdditionalConfigValue: "yay"
* }
*/
const { myConfig } = exampleModel.definition.settings;