diff --git a/core/router.js b/core/router.js index bb39ffd..730cc62 100644 --- a/core/router.js +++ b/core/router.js @@ -13,7 +13,7 @@ const globOptions = { } module.exports = function () { - const router = express.Router(); + const router = express.Router({ mergeParams: true }); router.get('/_health', (req, res, next) => { res.json({ diff --git a/helpers/controller.helper.js b/helpers/controller.helper.js index 1522cec..b78ebc7 100644 --- a/helpers/controller.helper.js +++ b/helpers/controller.helper.js @@ -106,6 +106,7 @@ function setPaginationInfo(totalCount, res) { function extractParamsFromRequest(req, res, extraParams = {}) { const result = {}; + result.route = (req && req.route) ? req.route.path : null; result.params = (req && req.params) ? req.params : null; result.query = (req && req.query) ? req.query : null; diff --git a/helpers/service.helper.js b/helpers/service.helper.js index b72262f..4a552a7 100644 --- a/helpers/service.helper.js +++ b/helpers/service.helper.js @@ -44,29 +44,27 @@ function _debugModelInfo(model) { return; } -function getAssociationArrayFromModel(model) { - const result = []; +function foundModelAssociation(model, associationName) { + let result = false; - if (!model || typeof model.associations !== 'object') { - throw new Error("Model should have the 'associations' property."); - } - - Object.keys(model.associations).forEach(key => result.push(key)); - return result; -} - -function modelAssociationsToArray(model) { - const result = []; - - if (!model || typeof model.associations !== 'object') { + 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) => { - result[key] = model.associations[key]; - //result.push(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; } @@ -117,16 +115,41 @@ const parseParamsToFindOptions = (params) => { return result; } +function hasAssociation(params) { + return (params) ? ((params.params) ? ((params.params.association) ? params.params.association : false ) : false ) : false; +} const defaultOptions = {}; const generateService = (model, extraMethods = {}, options = defaultOptions) => { const defaultService = { + fetchAssociation: async(params, context) => { + const associationName = hasAssociation(params); + delete params.params.association; + + const associationInfo = foundModelAssociation(model, associationName); + if (associationInfo) { + const master = await defaultService.fetchOne(params, context); + console.log(master); + const details = { + rows: await master[associationInfo.getFunc](), + count: await master[associationInfo.countFunc]() + } + return details; + } else { + throw new Error('¡fetchAssociation error!'); + } + }, fetchAll: async (params, context) => { - const findOptions = parseParamsToFindOptions(params); - console.log(model); - return await model.findAndCountAll(findOptions); + if (hasAssociation(params)) { + return defaultService.fetchAssociation(params, context) + } else { + const findOptions = parseParamsToFindOptions(params); + const result = await model.findAndCountAll(findOptions); + console.log(result); + return result; + } }, fetchOne: async (params, context) => { diff --git a/modules/values/value.controller.js b/modules/values/value.controller.js index 0df12eb..1e7ea32 100644 --- a/modules/values/value.controller.js +++ b/modules/values/value.controller.js @@ -10,11 +10,11 @@ const MODULE_NAME = '[value.controller]'; const controllerOptions = { MODULE_NAME }; const extraControllers = { - findSpeakers: (req, res, next) => { + findSpeakers: async (req, res, next) => { const params = extractParamsFromRequest(req, res, {}); - console.log(params); try { - const result = ["hola"]; //await valueService.fetchAll(params, { user: req.user }); + const result = await valueService.associationFetchAll(params, { user: req.user }); + console.log(result); return handleResultResponse(result, result.count, params, res); } catch (error) { handleErrorResponse(MODULE_NAME, 'findNext', error, res); diff --git a/modules/values/value.routes.js b/modules/values/value.routes.js index 495cbe8..95aa4cd 100644 --- a/modules/values/value.routes.js +++ b/modules/values/value.routes.js @@ -28,7 +28,18 @@ routes.get('/values/:id', valueController.findOne ); -/*routes.get('/values/:id/speakers', +routes.get('/values/:id/:association', + //isLoggedUser, + /*FieldMiddleware.middleware({ + invalidFields: ['createdAt'] + }),*/ + //PaginateMiddleware.middleware(), + //SortMiddleware.middleware({ default: "name" }), + valueController.find, +); + + +routes.get('/values/:id/speakers/:speakerId', //isLoggedUser, FieldMiddleware.middleware({ invalidFields: ['createdAt'] @@ -36,7 +47,7 @@ routes.get('/values/:id', PaginateMiddleware.middleware(), SortMiddleware.middleware({ default: "name" }), valueController.findSpeakers -);*/ +); module.exports = routes; \ No newline at end of file diff --git a/modules/values/value.service.js b/modules/values/value.service.js index 41973b4..9eb3e1e 100644 --- a/modules/values/value.service.js +++ b/modules/values/value.service.js @@ -6,7 +6,109 @@ const { generateService, parseParamsToFindOptions } = require('../../helpers/ser 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); \ No newline at end of file