Posted On January 13, 2022

Create your own custom mixin in LoopBack NodeJs

Ghazal Ehsan 0 comments
Hut Explore >> Technology , Programming >> Create your own custom mixin in LoopBack NodeJs
practice javascript and learn functions 400x277 1

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 the mixins 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 options parameter 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

https://medium.com/@ghazaltaimur27/create-your-own-custom-mixin-in-loopback-nodejs-f5a30583a193

Leave a Reply

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

Related Post

Latest Apple OS betas deliver Face ID with a mask and Universal Control

Latest Apple OS betas deliver Face ID with a mask and universal control. Apple just…

WhatsApp Now Lets You Transfer Data From Android to iPhone

WhatsApp users area unit finally obtaining the flexibility to transfer their information (chat history) from…

Change File upload limit in ngnix in AWS Server

When uploading image greater than 1 MB, it gives 413 Request entity too large error. Ngnix default…