Create your own custom mixin in LoopBack NodeJs

A mixin is nothing more than a method of two parameters: function(Model, options):

  1. “Model” is the model on which the mixin will be applied
  2. “options” are the options that may be defined in the model.json under themixins key. To add a mixin you only need to add mixinName: true. If instead of true you provide an object, then this object is the optionsparameter of the mixin function.

Step-by-step guide:

Following steps involved to create a mixin in loopback:

  1. First create a mixins folder in project/common directory.
  2. Now, create a file mixinName.js (any name) in mixins folder.
  3. 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:

  1. mixinName.js

Leave a Reply

Your email address will not be published. Required fields are marked *