A mixin is nothing more than a method of two parameters:
function(Model, options):
- “Model” is the model on which the mixin will be applied
- “options” are the options that may be defined in the
model.jsonunder themixinskey. To add a mixin you only need to addmixinName: true. If instead oftrueyou provide an object, then this object is theoptionsparameter of the mixin function.
Step-by-step guide:
Following steps involved to create a mixin in loopback:
- First create a mixins folder in project/common directory.
- Now, create a file mixinName.js (any name) in mixins folder.
- Open a file and write a following code:
'use strict';
module.exports = function(Model, options) {
Model.observe('before save', addConsoleLog);
};
let addConsoleLog = function(ctx, next) {
if (ctx.instance) {
console.log("Model instance is", ctx.instance);
}
next();
}
You will add any observer in your custom mixin.
4. After this add your custom mixin in any model json e.g Account.json.
{
"name": "Account",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"mixins": {
mixinName: true
},
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
This is it! Here are the links to the corresponding files in my project:
https://medium.com/@ghazaltaimur27/create-your-own-custom-mixin-in-loopback-nodejs-f5a30583a193
Categories: