UNPKG

yekonga-server

Version:
1,088 lines (909 loc) 65.5 kB
// @ts-nocheck /*global Yekonga */ // @ts-ignore const H = Yekonga.Helper; // @ts-ignore const Config = Yekonga.Config; function customActionCallback(action, name, params, isAdmin) { const { accessRole, route } = params || {} if (!isAdmin && Yekonga.CloudService.Actions[name]) { if(typeof accessRole == 'string') { if(typeof route == 'string') { if( Yekonga.CloudService.Actions[name][accessRole] && Yekonga.CloudService.Actions[name][accessRole][route] && Yekonga.CloudService.Actions[name][accessRole][route][action] ) { return Yekonga.CloudService.Actions[name][accessRole][route][action]; } } else if( Yekonga.CloudService.Actions[name][accessRole] && Yekonga.CloudService.Actions[name][accessRole][action] ) { return Yekonga.CloudService.Actions[name][accessRole][action]; } else if( Yekonga.CloudService.Actions[name][route] && Yekonga.CloudService.Actions[name][route][action] ) { return Yekonga.CloudService.Actions[name][route][action]; } } if(Yekonga.CloudService.Actions[name][action]) { return Yekonga.CloudService.Actions[name][action]; } } return null; } module.exports = class Resolver { constructor(model) { this.model = model; this.collection = null; this.modelClass = null; this.modelClassVariable = null; this.secondaryKey = null; this.modelFields = {}; this.validFields = []; this.keys = []; this.childrenKeys = []; this.parentKeys = []; this.parents = []; this.children = []; this.parentsObject = []; this.childrenObject = {}; this.resolver = {}; this.fileFields = []; this.timestampFields = []; this.arrayFields = []; this.childrenVariables = {} this.setModel(model); } setModel(model) { this.model = model; if (this.model._id) { this.collection = this.model._id.collection; this.modelClass = H.getClass(this.collection); this.modelClassVariable = H.getVariable(this.collection, true); if (!this.model._id.secondaryKey) { this.model._id.secondaryKey = H.getVariable(`${H.toSingular(H.getUnderscore(this.collection))}_id`); } this.secondaryKey = this.model._id.secondaryKey; } for (const key in this.model) { if (key == '_id') continue; this.keys.push(key); this.validFields.push(key); if (H.isTimestampColumn(key, this.model[key])) { this.timestampFields.push(key); } else if(H.isColumnUrl(key, this.model[key])) { this.fileFields.push(key); } else if(H.isColumnArray(key, this.model[key])) { this.arrayFields.push(key) } } this.modelFields = model; this.parents = H.getParents(this.model); this.children = H.getChildren(this.model); this.parentsData = {}; this.childrenData = {}; this.resolver = { Query: {}, Mutation: {}, } for (const item of this.parents) { this.parentKeys.push(item._id.relatedName); this.parentsData[item._id.relatedName] = H.copyJson(item._id); } for (const item of this.children) { const relatedName = item._id.relatedName; this.childrenKeys.push(relatedName); this.childrenData[relatedName] = H.copyJson(item._id); this.childrenObject[relatedName] = H.copyJson(item); const collection = item._id.collection; const childSecondaryKey = H.getVariable(`${H.toSingular(collection)}_id`) const childModelClass = H.getClass(H.toSingular(collection)); const childModelClassVariable = H.getClassVariable(collection, true); const childClassVariableOne = H.getVariable(H.toSingular(relatedName)); const childClassVariableMany = H.getVariable(H.toPlural(relatedName)); const createChild = H.getVariable(`create_${H.toSingular(childModelClassVariable)}`, true); const updateChild = H.getVariable(`update_${H.toSingular(childModelClassVariable)}`, true); const deleteChild = H.getVariable(`delete_${H.toSingular(childModelClassVariable)}`, true); this.childrenVariables[relatedName] = { collection, childSecondaryKey, relatedName, childModelClass, childModelClassVariable, childClassVariableOne, childClassVariableMany, createChild, updateChild, deleteChild, } } } create() { this.createQuery(); this.createMutation(); this.createChildren(); this.createParent(); return this.resolver; } createQuery() { const $this = this; const authentication = this.authentication; const model = this.model; const secondaryKey = this.secondaryKey; const modelClass = this.modelClass; const modelClassVariable = this.modelClassVariable; const validFields = this.validFields; const keys = this.keys; const parentKeys = this.parentKeys; const childrenKeys = this.childrenKeys; const timestampFields = this.timestampFields; const getValidFields = this.getValidFields; const findSingle = this.modelClassVariable; this.setSchemaReference(findSingle); // @ts-ignore this.resolver.Query[findSingle] = Yekonga.Cloud.getQueryResolver(findSingle) ? // @ts-ignore Yekonga.Cloud.getQueryResolver(findSingle) : // @ts-ignore async function(parent, params, context, info) { authentication(modelClass, `Query.${findSingle}`, `${modelClassVariable}.information`); var parentParams = (parent && parent.__params) ? parent.__params: {}; if (parent && parent[findSingle]) { return parent[findSingle]; } if(parentParams) { if(!params.route && parentParams.route) params.route = parentParams.route; if(!params.accessRole && parentParams.accessRole) params.accessRole = parentParams.accessRole; } if (!context) context = {}; context.params = params; context.parent = parent; context.accessRole = params.accessRole; // @ts-ignore var result = await Yekonga.Model[modelClass].findOne(params.where, context); if(result) { result[`__params`] = H.copyJson(params); } return result; } const findMany = H.toPlural(this.modelClassVariable); this.setSchemaReference(findMany); // @ts-ignore this.resolver.Query[findMany] = Yekonga.Cloud.getQueryResolver(findMany) ? // @ts-ignore Yekonga.Cloud.getQueryResolver(findMany) : async function(parent, params, context, info) { // Yekonga.time(`Query.${findMany}`); authentication(modelClass, `Query.${findMany}`, `${modelClassVariable}.list`); var parentParams = (parent && parent.__params) ? parent.__params: {}; if (!params) params = {}; if (parent && parent[findMany]) { return parent[findMany]; } if(parentParams) { if(!params.route && parentParams.route) params.route = parentParams.route; if(!params.accessRole && parentParams.accessRole) params.accessRole = parentParams.accessRole; } if (!context) context = {}; context.params = params; context.parent = parent; var selectedFields = H.graphqlFields(info); // @ts-ignore var result = []; if (selectedFields['_groupList'] || selectedFields['_groupSummary']) { var groupContext = { res: context.res, req: context.req, Auth: H.copyJson(context.Auth), Client: H.copyJson(context.Client), params: H.copyJson(context.params), } if(!groupContext.params) groupContext.params = {}; if(!groupContext.params.groupBy) groupContext.params.groupBy = {}; if(!groupContext.params.orderBy) groupContext.params.orderBy = []; var groupByFields = {}; for (const key in selectedFields) { if (key != '_groupList' && key != '_groupSummary') { var __params = selectedFields[key].params; if (__params && __params.format && Yekonga.Graphql.Resolvers[modelClass][key]) { groupByFields[key] = { $dateToString: { format: H.formatJsToMongo(__params.format.value), date: `$${key}` } }; } else { groupByFields[key] = `$${key}`; } } } groupContext.params.groupBy = { ...groupByFields } if(params.groupOrderBy) { if(params.groupOrderBy.key) { groupContext.params.orderBy.push({ key:`_id.${params.groupOrderBy.key}`, value: params.groupOrderBy.value, }); } else { groupContext.params.orderBy.push({ key:`_id`, value: params.groupOrderBy.value, }); } } else if(!params.orderBy) { groupContext.params.orderBy.push({key:'_id', value:'DESC'}); } if(groupContext.params.orderBy) { if(Array.isArray(groupContext.params.orderBy)) { for (let i = 0; i < groupContext.params.orderBy.length; i++) { if(groupContext.params.orderBy[i].key && !groupContext.params.orderBy[i].key.startsWith('_id')) groupContext.params.orderBy[i].key = `_id.${groupContext.params.orderBy[i].key}`; } } else if(groupContext.params.orderBy.key && !groupContext.params.orderBy.key.startsWith('_id')) { groupContext.params.orderBy.key = `_id.${groupContext.params.orderBy.key}`; } } result = await Yekonga.Model[modelClass].find(params.where, groupContext); for (let i = 0; i < result.length; i++) { result[i][`__params`] = H.copyJson(params); if(Array.isArray(groupByFields)) { for (const key of groupByFields) { if (timestampFields.includes(key) && selectedFields[key].params && selectedFields[key].params.format) { result[i][`_${key}`] = selectedFields[key].params.format.value; } } } else if(groupByFields) { for (const key in groupByFields) { if (timestampFields.includes(key) && selectedFields[key].params && selectedFields[key].params.format) { result[i][`_${key}`] = selectedFields[key].params.format.value; } } } } } else { result = await Yekonga.Model[modelClass].find(params.where, context); for (let i = 0; i < result.length; i++) { result[i][`__params`] = H.copyJson(params); } } // Yekonga.timeEnd(`Query.${findMany}`); return result; } const findPaginate = H.getVariable(`${this.modelClass}Paginate`); this.setSchemaReference(findPaginate); // @ts-ignore this.resolver.Query[findPaginate] = Yekonga.Cloud.getQueryResolver(findPaginate) ? // @ts-ignore Yekonga.Cloud.getQueryResolver(findPaginate) : async function(parent, params, context, info) { authentication(modelClass, `Query.${findPaginate}`, `${modelClassVariable}.list`); var parentParams = (parent && parent.__params) ? parent.__params: {}; if (!params) params = {}; if (parent && parent[findPaginate]) { return parent[findPaginate]; } if(parentParams) { if(!params.route && parentParams.route) params.route = parentParams.route; if(!params.accessRole && parentParams.accessRole) params.accessRole = parentParams.accessRole; } if (!context) context = {}; context.params = params; context.parent = parent; // @ts-ignore var result = await Yekonga.Model[modelClass].paginate(params.where, context); if(Array.isArray(result.data)) { for (let i = 0; i < result.data.length; i++) { result.data[i][`__params`] = H.copyJson(params); } } return result; } const findDownload = H.getVariable(`download_${H.toPlural(this.collection)}`); this.setSchemaReference(findDownload); // @ts-ignore this.resolver.Query[findDownload] = Yekonga.Cloud.getQueryResolver(findDownload) ? // @ts-ignore Yekonga.Cloud.getQueryResolver(findDownload) : async function(parent, params, context, info) { authentication(modelClass, `Query.${findDownload}`, `${modelClassVariable}.download`); var parentParams = (parent && parent.__params) ? parent.__params: {}; if (!params) params = {}; if (parent && parent[findDownload]) { return parent[findDownload]; } if(parentParams) { if(!params.route && parentParams.route) params.route = parentParams.route; if(!params.accessRole && parentParams.accessRole) params.accessRole = parentParams.accessRole; } if (!context) context = {}; context.params = params; context.parent = parent; // @ts-ignore var result = await Yekonga.Model[modelClass].download(params.where, context); return result; } const findSummary = H.getVariable(`${this.modelClassVariable}Summary`); this.setSchemaReference(findSummary); // @ts-ignore this.resolver.Query[findSummary] = Yekonga.Cloud.getQueryResolver(findSummary) ? // @ts-ignore Yekonga.Cloud.getQueryResolver(findSummary) : async function(parent, params, context, info) { // console.log(info); authentication(modelClass, `Query.${findSummary}`, `${modelClassVariable}.summary`); var parentParams = (parent && parent.__params) ? parent.__params: {}; if (!params) params = {}; if (parent && parent[findSummary]) { return parent[findSummary]; } if(parentParams) { if(!params.route && parentParams.route) params.route = parentParams.route; if(!params.accessRole && parentParams.accessRole) params.accessRole = parentParams.accessRole; } if (!context) context = {}; context.params = params; context.parent = parent; var __parent = (parent)? H.copyJson(parent): {}; __parent.__params = H.copyJson(params); return __parent; } const summaryFunction = async function(action, parent, params, context, info) { var parentParams = (parent && parent.__params) ? parent.__params: {}; if (!context) context = {}; if (!params) params = {}; if (!params.where) params.where = {}; if (parentParams) { if(parentParams.where) { for (const key in parentParams.where) { const value = parentParams.where[key]; if (!params.where[key]) { params.where[key] = value; } } } if(!params.route && parentParams.route) { params.route = parentParams.route; } if(!params.accessRole && parentParams.accessRole) { params.accessRole = parentParams.accessRole; } if(!params.groupBy && parentParams.groupBy) { params.groupBy = parentParams.groupBy; } if(!params.orderBy && parentParams.orderBy) { params.orderBy = parentParams.orderBy; } if(!params.addedFields && parentParams.addedFields) { params.addedFields = parentParams.addedFields; } } if(parent && parent.__ && parent.__.collection) { for (const row of $this.parents) { if(row._id.collection == parent.__.collection && typeof parent[row._id.secondaryKey] != 'undefined') { params.where[row._id.foreignKey] = { equalTo: parent[row._id.secondaryKey] }; break; } } } context.params = params; context.parent = parent; // @ts-ignore var result = await ((Yekonga.Model[modelClass][action]) ? Yekonga.Model[modelClass][action](params.where, context) : null); if(result && typeof result == 'object') result.__params = H.copyJson(params); return result; } const objectSummary = H.getClass(`${modelClass}Summary`); // @ts-ignore this.resolver[objectSummary] = Yekonga.Cloud.getResolver(objectSummary) ? // @ts-ignore Yekonga.Cloud.getResolver(objectSummary) : { count: async function(parent, params, context, info) { return await summaryFunction('count', parent, params, context, info); }, sum: async function(parent, params, context, info) { return await summaryFunction('sum', parent, params, context, info); }, max: async function(parent, params, context, info) { return await summaryFunction('max', parent, params, context, info); }, min: async function(parent, params, context, info) { return await summaryFunction('min', parent, params, context, info); }, graph: async function(parent, params, context, info) { return await summaryFunction('graph', parent, params, context, info); }, } if (!this.resolver[modelClass]) this.resolver[modelClass] = {} // @ts-ignore this.resolver[modelClass]['_field'] = async function(data, params, context, info) { if (params.formula) { var args = []; for (const key in data) { args.push(key); } const formulaString = `(function({${args.join(', ')}}) { return ${params.formula}; })`; var formulaFunction = eval(formulaString); var value = formulaFunction(data); return value; } else if (params && params.action) { const action = params.action; if (action == 'CONCAT') { var values = []; for (const key of params.targets) { values.push(data[key]); } return values.join(' '); } else if (action == 'PRODUCT') { var values = []; for (const key of params.targets) { var v = parseFloat(data[key]); values.push((v == NaN) ? 0 : v); } return values.reduce((a, b) => a * b); } else if (action == 'DATE' || action == 'TIME') { var value = ""; if(Array.isArray(params.targets)) { for (const key of params.targets) { if(params.format) { value += H.toTimestampString(data[key], params.format); } else { value += H.toTimestampString(data[key]); } } } else if(params.target) { if(params.format) { value = H.toTimestampString(data[params.target], params.format); } else { value = H.toTimestampString(data[params.target]); } } return value; } } else if (params.format) { var value = "No target"; if(params.target) { value = H.toTimestampString(data[params.target], params.format); } else if(params.targets) { value = ""; for (const key of params.targets) { value += H.toTimestampString(data[key], params.format); } } return value; } return null; } // @ts-ignore this.resolver[modelClass]['_groupList'] = async function(data, params, context, info) { var parentParams = (data && data.__params) ? data.__params: {}; var currentParams = {} if (!context) context = {}; if (!context.params) context.params = params || {} if (!context.params.where) context.params.where = params.where || {} if (!context.params.addedFields) context.params.addedFields = {} context.params.groupBy = null; currentParams = H.copyJson(params); if(!currentParams) currentParams = {} if(!currentParams.where) currentParams.where = {} if(parentParams) { if(parentParams.route) currentParams.route = parentParams.route; if(parentParams.accessRole) currentParams.accessRole = parentParams.accessRole; context.params.route = currentParams.route; context.params.accessRole = currentParams.accessRole; if(!context.params.groupBy && parentParams.groupBy) { context.params.groupBy = parentParams.groupBy; } if(!context.params.orderBy && parentParams.orderBy) { context.params.orderBy = parentParams.orderBy; } if(!context.params.addedFields && parentParams.addedFields) { context.params.addedFields = parentParams.addedFields; } if(parentParams.where) { for (const key in parentParams.where) { const value = parentParams.where[key]; if (!currentParams.where[key]) { currentParams.where[key] = value; } } } } for (const key in data) { if (!key.startsWith('_')) { if (Object.hasOwnProperty.call(data, `_${key}`)) { context.params.addedFields[`_${key}`] = { $dateToString: { format: H.formatJsToMongo(data[`_${key}`]), date: `$${key}` } } currentParams.where[`_${key}`] = data[key]; } else { currentParams.where[key] = data[key]; } } } if(Array.isArray(currentParams.where.OR) && currentParams.where.OR.length) { let _where = {OR:[]} for (const e of currentParams.where.OR) { for (const key in currentParams.where) { if (!['OR'].includes(key)&& Object.hasOwnProperty.call(currentParams.where, key)) { e[key] = currentParams.where[key]; } } _where.OR.push(e); } currentParams.where = H.copyJson(_where); } var result = await Yekonga.Model[modelClass].find(currentParams.where, context); if(Array.isArray(result)) { for (let i = 0; i < result.length; i++) { result[i].__params = H.copyJson(context.params); } } return result; } // @ts-ignore this.resolver[modelClass]['_groupSummary'] = async function(data, params, context, info) { authentication(modelClass, `Query.${findSummary}`, `${modelClassVariable}._groupSummary`); var parentParams = (data && data.__params) ? data.__params: {}; if (!params) params = {}; if (data && data[findSummary]) { return data[findSummary]; } if (!context) context = {}; if (!context.params) context.params = params || {} if (!context.params.where) context.params.where = params.where || {} if (!context.params.addedFields) context.params.addedFields = {} context.params.groupBy = null; if(parentParams) { if(parentParams.route) context.params.route = parentParams.route; if(parentParams.accessRole) context.params.accessRole = parentParams.accessRole; if(parentParams.where) { for (const key in parentParams.where) { const value = parentParams.where[key]; if (!context.params.where[key]) { context.params.where[key] = value; } } } } if(Array.isArray(context.params.where.OR) && context.params.where.OR.length) { let _where = {OR:[]} for (const e of context.params.where.OR) { for (const key in context.params.where) { if (!['OR'].includes(key)&& Object.hasOwnProperty.call(context.params.where, key)) { e[key] = context.params.where[key]; } } _where.OR.push(e); } context.params.where = H.copyJson(_where); } for (const key in data) { if (!key.startsWith('_')) { if (Object.hasOwnProperty.call(data, `_${key}`)) { context.params.addedFields[`_${key}`] = { $dateToString: { format: H.formatJsToMongo(data[`_${key}`]), date: `$${key}` } } context.params.where[`_${key}`] = data[key]; } else { context.params.where[key] = data[key]; } } } var __parent = (data)? H.copyJson(data): {}; __parent.__params = H.copyJson(context.params); return __parent; } // @ts-ignore this.resolver[modelClass]['_auditTrails'] = async function(data, params, context, info) { var where = { model: modelClass }; if (!context) context = {}; if (!context.params) context.params = params || {} if (!context.params.where) context.params.where = params.where || {} context.params.orderBy = { key: "createdAt", value: "DESC" } var document = (context.params.old)? data[secondaryKey]: data['_id']; where.document = document; if(context.params && context.params.where) { for (const key in context.params.where) { const value = context.params.where[key]; if(['newValues','oldValues'].includes(key)) { if(value && typeof value == 'object') { for (const key2 in value) { if (Object.hasOwnProperty.call(value, key2)) { const value2 = value[key2]; where[`${key}.${key2}`] = value2; } } } } else if (!where[key]) { where[key] = value; } } } // console.log(where) var result = await Yekonga.Model.AuditTrail.find(where, context, true); return result; } for (const key in this.modelFields) { const fieldKey = H.getVariable(key); const testKey = H.getUnderscore(key); const field = this.modelFields[key]; if (fieldKey == 'password' || field.protected) continue; if (modelClass == 'User' && fieldKey.includes('token')) continue; if (H.isTimestampColumn(key, field)) { if (!this.resolver[modelClass]) this.resolver[modelClass] = {} // @ts-ignore this.resolver[modelClass][fieldKey] = async function(data, params, context, info) { if (data[fieldKey] && params && params.format) { return H.toTimestampString(data[fieldKey], params.format); } return data[fieldKey]; } } else if (H.isColumnUrl(key, field)) { if (!this.resolver[modelClass]) this.resolver[modelClass] = {} this.resolver[modelClass][fieldKey] = async function(data, params, context, info) { const { req, res } = context || {}; var value = data[fieldKey]; var images = []; var _values = (Array.isArray(value)) ? value : (value ? [value] : []); var defaultImage = Yekonga.Helper.getBaseUrl(`img/placeholder.jpg`, {req, res}); for (const val of _values) { if (val && typeof val === 'string' && val.trim() != '') { if (val.trim().startsWith('http') || val.trim().startsWith('//')) { images.push(val.trim()); } else { images.push(Yekonga.Helper.getBaseUrl(`uploads/${val}`, {req, res})); } } else { images.push(defaultImage); } } if (H.isColumnUrls(key, field)) { return images; } return (images.length) ? images.pop() : defaultImage; } } } } createMutation() { const self = this; const authentication = this.authentication; const model = this.model; const modelClass = this.modelClass; const modelClassVariable = this.modelClassVariable; const children = this.children; const secondaryKey = this.secondaryKey; const validFields = this.validFields; const keys = this.keys; const parentKeys = this.parentKeys; const childrenKeys = this.childrenKeys; const childrenVariables = this.childrenVariables; const childrenObject = this.childrenObject; const fileFields = this.fileFields; const getValidFields = this.getValidFields; const saveFunction = function(action, permission, isUpdate = false) { return async function(parent, params, context, info) { authentication(modelClass, action, permission); if (!context) context = {}; if (!params) params = {}; context.params = params; var input = (Array.isArray(params.input)) ? params.input : ((params.input) ? [params.input] : []); var validInput = getValidFields(input, model, !isUpdate, fileFields); var oneByOne = false; for (const row of children) { const childVariableOne = H.getVariable(H.toSingular(row._id.collection)); const childVariableMany = H.getVariable(H.toPlural(row._id.collection)); if (row._id.attribute) { for (let i = 0; i < validInput.length; i++) { if (input[i][childVariableOne]) { validInput[i][childVariableOne] = input[i][childVariableOne]; } else if (input[i][childVariableMany]) { validInput[i][childVariableMany] = input[i][childVariableMany]; } } } for (const row of input) { if (row[childVariableOne]) { oneByOne = true; } else if (row[childVariableMany]) { oneByOne = true; } } } var result = null; var resultData = null; if (!oneByOne) { if (isUpdate) { if (Array.isArray(validInput)) validInput = validInput.pop(); result = await Yekonga.Model[modelClass].update(validInput, params.where, {...context, parent, params, info });; } else { result = await Yekonga.Model[modelClass].create(validInput, {...context, parent, params, info }); } if (result && result.error) { return { error: true, status: false, success: false, message: result.error, affectedCount: 0 }; } else if (!result) { return { error: true, status: false, success: false, message: "Response is null" }; } resultData = (result && Array.isArray(result.data)) ? result.data : ((result.data) ? [result.data] : null) } else { resultData = []; const inputList = (Array.isArray(input)) ? input : [input]; if (inputList && inputList.length) { for (const _input of inputList) { var _validInput = getValidFields(_input, model, !isUpdate, fileFields); if (isUpdate) { if (Array.isArray(_validInput)) _validInput = _validInput.pop(); result = await Yekonga.Model[modelClass].update(_validInput, params.where, {...context, parent, params, info });; if(result && !result.error && result.data.length == 0) { result.data.push(await Yekonga.Model[modelClass].find(params.where, {...context, parent, params, info })); } } else { result = await Yekonga.Model[modelClass].create(_validInput, {...context, parent, params, info }); } var _resultData = (result && Array.isArray(result.data)) ? result.data[0] : ((result && result.data) ? result.data : null) if (_resultData) { for (const _key in _input) { if(!childrenObject[_key]) continue; const childParams = {...params } childParams.input = _input[_key]; if(!childParams.input) continue; const child = childrenObject[_key]; const childVar = childrenVariables[_key]; if ( Yekonga.Graphql.Resolvers && Yekonga.Graphql.Resolvers['Mutation'] && Yekonga.Graphql.Resolvers['Mutation'][childVar.createChild] && !child._id.attribute ) { if (!Array.isArray(childParams.input)) childParams.input = [childParams.input]; childParams.input = childParams.input.map((item, index, array) => { item[H.getVariable(child._id.foreignKey)] = _resultData[secondaryKey]; return item; }) var childResult = null; if (isUpdate) { let childrenWhere = {}; childrenWhere[H.getVariable(child._id.foreignKey)] = _resultData[secondaryKey]; let childrenList = await Yekonga.Model[childVar.childModelClass].find(childrenWhere, {...context, parent, params, info }); let childrenListIds = childrenList.map((item, index, array) => { return `${item[childVar.childSecondaryKey]}`; }) let updatedChildrenList = []; for (const row of childParams.input) { let _childParams = { where: {}, input: [] }; _childParams.input = [row]; _childParams.route = params.route; _childParams.accessRole = params.accessRole; if (childrenListIds.includes(`${row[childVar.childSecondaryKey]}`)) { updatedChildrenList.push(`${row[childVar.childSecondaryKey]}`); _childParams.where[childVar.childSecondaryKey] = { equalTo: row[childVar.childSecondaryKey] }; childResult = await Yekonga.Graphql.Resolvers['Mutation'][childVar.updateChild](_resultData, _childParams, context, info); } else { childResult = await Yekonga.Graphql.Resolvers['Mutation'][childVar.createChild](_resultData, _childParams, context, info); } } let deleteChildrenIds = childrenListIds.filter((id, index, array) => { return (id && !updatedChildrenList.includes(id)) ? true : false; }); if (deleteChildrenIds.length) { let deleteParams = { where: {}, accessRole: params.accessRole, route: params.route } deleteParams.where[childVar.childSecondaryKey] = { in: deleteChildrenIds } try { await Yekonga.Graphql.Resolvers['Mutation'][childVar.deleteChild](_resultData, deleteParams, context, info); } catch (error) { console.error(error); console.log("Fail to delete children"); } } } else { childResult = await Yekonga.Graphql.Resolvers['Mutation'][childVar.createChild](_resultData, childParams, context, info); } if (childResult && childResult.data && childVar.childModelClassVariable) { _resultData[childVar.childModelClassVariable] = (Array.isArray(childResult.data)) ? childResult.data : [childResult.data]; } } } resultData.push(_resultData); } } } } resultData = (resultData && resultData.length) ? resultData[0] : null; var returnMessage = (isUpdate) ? 'Data update success' : 'Data saved success'; return { error: false, success: true, status: true, message: returnMessage, data: resultData, affectedCount: result.affectedCount }; } } const importFunction = function(action, permission) { return async function(parent, params, context, info) { authentication(modelClass, action, permission); if (!context) context = {}; if (!params) params = {}; context.params = params; var input = (Array.isArray(params.input)) ? params.input : ((params.input) ? [params.input] : []); if(parent) parent.__params = params; // @ts-ignore let result = await Yekonga.Model[modelClass].import(input, {...context, parent, params, info }); if (result && result.error) { return { code: 400, status: false, success: false, message: result.error, response: null }; } else if (!result) { return { code: 400, status: false, success: false, message: "Response is null", response: null }; } return result; } } var createResolver = H.getVariable(`create_${this.modelClassVariable}`); this.setSchemaReference(createResolver); // @ts-ignore this.resolver.Mutation[createResolver] = Yekonga.Cloud.getMutationResolver(createResolver) ? // @ts-ignore Yekonga.Cloud.getMutationResolver(createResolver) : saveFunction(`Mutation.${createResolver}`, `${modelClassVariable}.create`, false); var updateResolver = H.getVariable(`update_${this.modelClassVariable}`); this.setSchemaReference(updateResolver); // @ts-ignore this.resolver.Mutation[updateResolver] = Yekonga.Cloud.getMutationResolver(updateResolver) ? // @ts-ignore Yekonga.Cloud.getMutationResolver(updateResolver) : saveFunction(`Mutation.${updateResolver}`, `${modelClassVariable}.edit`, true); var importResolver = H.getVariable(`import_${H.toPlural(this.collection)}`); this.setSchemaReference(updateResolver); // @ts-ignore this.resolver.Mutation[importResolver] = Yekonga.Cloud.getMutationResolver(importResolver) ? // @ts-ignore Yekonga.Cloud.getMutationResolver(importResolver) : importFunction(`Mutation.${importResolver}`, `${modelClassVariable}.import`); var deleteResolver = H.getVariable(`delete_${this.modelClassVariable}`); this.setSchemaReference(deleteResolver); // @ts-ignore this.resolver.Mutation[deleteResolver] = Yekonga.Cloud.getMutationResolver(deleteResolver) ? // @ts-ignore Yekonga.Cloud.getMutationResolver(deleteResolver) : async function(parent, params, context, info) { authentication(modelClass, `Mutation.${deleteResolver}`, `${modelClassVariable}.delete`); if (!context) context = {}; if (!params) params = {}; context.params = params; // @ts-ignore var result = await Yekonga.Model[modelClass].delete(params.where, {...context, parent, params, info }); if (result && result.error) { return { error: true, status: false, success: false, message: result.error.message, affectedCount: 0 }; } else if (!result) { return { error: true, status: false, success: false, message: "Response is null" }; } return { error: false, status: true, success: true, message: 'Data deleted success', affectedCount: result.affectedCount }; } var actionResolver = H.getVariable(`${this.modelClassVariable}_action`); this.setSchemaReference(actionResolver); // @ts-ignore this.resolver.Mutation[actionResolver] = Yekonga.Cloud.getMutationResolver(actionResolver) ? // @ts-ignore Yekonga.Cloud.getMutationResolver(actionResolver) : async function(parent, params, context, info) { authentication(modelClass, `Mutation.${actionResolver}`, `${modelClassVariable}.action`); if (!context) context = {}; if (!params) params = {}; context.params = params; var result = { data: { affectedCount: 0 } } var injectFunction = customActionCallback(params.action, modelClass, params, false); if (injectFunction) { if(parent) parent.__params = params; result = await injectFunction({...context, parent, params, info }); } else { return { error: true, st