Skip to content

Instantly share code, notes, and snippets.

@ghazaltaimur13
Created September 21, 2018 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghazaltaimur13/163c66550af5cedd75941f03eefc4fce to your computer and use it in GitHub Desktop.
Save ghazaltaimur13/163c66550af5cedd75941f03eefc4fce to your computer and use it in GitHub Desktop.
BelongsTo Required relation Mixin in loopback NodeJs
'use strict';
let _ = require('lodash');
module.exports = function(Model, options) {
Model.observe('before save', checkBelongsToIntegrity);
};
let checkBelongsToIntegrity = function(ctx, next) {
if (ctx.instance) {
let Model = ctx.Model;
let msg = '';
let promiseArray = [];
let relationsArray = relationsArrayData(ctx);
relationsArray.forEach(function(relation) {
if (relation.type == 'belongsTo') {
let parentModelName = relation.modelName;
let parentModel = Model.app.models[parentModelName];
let parentId = '';
let keyName = parentModelName.charAt(0).toLowerCase() + parentModelName.slice(1) + 'Id';
if (relation.fk) {
parentId = ctx.instance[relation.fk];
} else {
parentId = ctx.instance[keyName];
}
if (parentId) {
if (parentId != 0) {
promiseArray.push(parentModel.findById(parentId).then(function(parentInstance) {
if (parentInstance === null) {
msg += 'No ' + parentModelName + ' with "' + parentId + '" id. ';
}
}));
} else {
msg += 'No ' + parentModelName + ' with "' + parentId + '" id. ';
promiseArray.push(msg);
}
} else if (relation.fkReq == true) {
msg += parentModelName + ' Id is required.';
promiseArray.push(msg);
} else {
if (parentId == 0) {
msg += 'No ' + parentModelName + ' with "' + parentId + '" id. ';
promiseArray.push(msg);
}
}
}
});
if (promiseArray.length > 0) {
Promise.all(promiseArray).then(function() {
next(msg);
}, console.error).catch(function(err) {
next(err);
});
} else {
next();
}
} else {
next();
}
};
let relationsArrayData = function(ctx) {
let relations = ctx.Model.definition.settings.relations;
let relationsArray = _.map(relations, rel => {
return {modelName: rel.model,
fkReq: rel.foreignKeyRequired, fk: rel.foreignKey, type: rel.type};
});
return relationsArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment