module.exports = Self => { Self.remoteMethodCtx('getLeaves', { description: 'Returns the nodes for a zone', accepts: [ { arg: 'id', type: 'number', description: 'The zone id', http: {source: 'path'}, required: true }, { arg: 'parentId', type: 'number', description: 'Get the children of the specified father', }, { arg: 'search', type: 'string', description: 'Filter nodes whose name starts with', } ], returns: { type: ['object'], root: true }, http: { path: `/:id/getLeaves`, verb: 'GET' } }); Self.getLeaves = async(ctx, id, parentId = null, search, options) => { const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); const [res] = await Self.rawSql( `CALL zone_getLeaves(?, ?, ?, FALSE)`, [id, parentId, search], myOptions ); const map = new Map(); for (let node of res) { if (!map.has(node.parentFk)) map.set(node.parentFk, []); map.get(node.parentFk).push(node); } function setLeaves(nodes) { if (!nodes) return; for (let node of nodes) { node.childs = map.get(node.id); setLeaves(node.childs); } } const leaves = map.get(parentId); const maxNodes = 250; if (res.length <= maxNodes) setLeaves(leaves); return leaves || []; }; };