DO $$ plv8.elog(INFO, '------------------------------------update user menus start------------------------------------'); buildTree = function(list) { try { let temp = {}; let tree = {}; for (let menu of list) { temp[menu.id] = menu; } for (let i in temp) { if (temp[i].parent) { if (!temp[temp[i].parent].children) { temp[temp[i].parent].children = {}; } temp[temp[i].parent].children[temp[i].id] = temp[i]; } else {
getTreeOfMenus = function() { let cmdb = require('xxx'); let result = cmdb.service.query('default', '{xxx{id name}}', {}); return buildTree(result); }; let allMenus = getTreeOfMenus();
delete allMenus['xxx'];
let ids = []; idsOfflatten = function(data) { try { for (let id in data) { ids.push(id); if (data[id].children) { idsOfflatten(data[id].children); } } return ids; } catch (error) { plv8.elog(ERROR, 'idsOfflatten ' + error); } }; let flatIds = idsOfflatten(allMenus); plv8.elog(INFO, 'new menu ids:' + flatIds); getNormalMenus = function(menus) { try { plv8.elog(INFO, 'old menus : ' + JSON.stringify(menus)); let old_keys = Object.keys(menus); old_keys.forEach(id => { if (!flatIds.includes(id)) { plv8.elog(INFO, 'delete menu id: ' + id); delete menus[id]; } }); return menus; } catch (error) { plv8.elog(ERROR, 'getNormalMenus ' + error); } };
updateMenus = function() { try { let ROLE_ADMIN = 'admin', ROLE_DOMAIN = 'domain'; let query = 'SELECT name, menus, role_type FROM xxx'; let updateAdmin = 'UPDATE xxx SET menus=NULL, last_modified=CURRENT_TIMESTAMP where name = $1'; let updateNormal = 'UPDATE xxx SET menus=$1, last_modified=CURRENT_TIMESTAMP where name = $2'; let execCount=0; plv8.execute(query).forEach(row => { let roleType = row.role_type; if (roleType === ROLE_DOMAIN || roleType === ROLE_ADMIN) { let adminCount = plv8.execute(updateAdmin, [row.name]); plv8.elog(INFO, 'update admin user menus is null ,count: '+adminCount ); adminCount>0 ? execCount+=1:null; return; }
let newMenus = getNormalMenus(row.menus); let normalCount = plv8.execute(updateNormal, [newMenus, row.name]); plv8.elog(INFO, 'update normal user menus , ' + JSON.stringify(newMenus)+',count:'+normalCount); normalCount>0 ? execCount+=1:null; });
let updateCount=updateMenus(); plv8.elog(INFO,'total of successes :'+updateCount); plv8.elog(INFO,'------------------------------------update user menus end------------------------------------'); $$ LANGUAGE plv8;