app2-api/modules/values/value.service.js
2019-07-09 22:13:41 +02:00

114 lines
3.4 KiB
JavaScript

/* global Venue */
'use strict';
const _ = require('lodash');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const Sequelize = require('sequelize');
const models = require('../../core/models');
function modelAssociationsToArray(model) {
const result = [];
if (typeof model !== 'function' || typeof model.associations !== 'object') {
throw new Error("Model should be an object with the 'associations' property.");
}
Object.keys(model.associations).forEach((key) => {
const association = {};
// all needed information in the 'options' object
if (model.associations[key].hasOwnProperty('options')) {
association[key] = model.associations[key] //.options;
}
result.push(association);
});
return result;
}
function findModelAssociationByForeignIdentifier(model, foreignId) {
if (typeof model !== 'function' || typeof model.associations !== 'object') {
throw new Error("Model should be an object with the 'associations' property.");
}
Object.keys(model.associations).forEach((key) => {
if (model.association[key].foreignIdentifier === foreignId) {
console.log('encontrado');
const accessors = model.association[key].accessors;
return {
name: model.association[key].as,
type: model.association[key].associationType,
accessors: accessors,
countFunc: accessors['count'],
getFunc: accessors['get'],
}
}
});
return false;
}
function foundModelAssociation(model, associationName) {
let result = false;
if (typeof model !== 'function' || typeof model.associations !== 'object') {
throw new Error("Model should be an object with the 'associations' property.");
};
Object.keys(model.associations).forEach((key) => {
const nameAs = model.associations[key].as;
if (nameAs.toUpperCase() == associationName.toUpperCase()) {
const item = model.associations[key];
const accessors = item.accessors;
result = {
name: item.as,
type: item.associationType,
accessors: accessors,
countFunc: accessors['count'],
getFunc: accessors['get'],
}
}
})
return result;
}
function extractParams(params) {
const result = [];
Object.keys(params).forEach((key, item) => {
result[key] = item
});
return result;
}
const extraMethods = {
associationFetchAll: async (params, context) => {
async function fetchOne(params, context) {
const findOptions = parseParamsToFindOptions(params);
return await model.findOne({
where: findOptions.where,
include: findOptions.include
});
};
const model = models.Value;
const associationName = params.params.association;
delete params.params.association;
const associationInfo = foundModelAssociation(model, associationName);
if (associationInfo) {
const result = await fetchOne(params, context);
const prueba = await result[associationInfo.getFunc]();
return prueba;
} else {
throw new Error('error');
}
}
};
module.exports = generateService(models.Value, extraMethods);