Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.