app/extend/application.js
module.exports = {
formatTime(time){
let d = new Date(time);
const Month = (d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) : '0'+(d.getMonth() + 1)
const Day = d.getDate() >= 10 ? d.getDate() : '0' + d.getDate()
const h = d.getHours() >= 10 ? d.getHours() : '0' + d.getHours()
const m = d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes()
const s = d.getSeconds() >= 10 ? d.getSeconds() : '0' + d.getSeconds()
return d.getFullYear() + '-' + Month + '-' + Day + ' ' + h + ':' + m + ':' + s;
},
//生成唯一的id id是字符串 用作离线模式id的生产
GenNonDuplicateID(){
let idStr = Date.now().toString(36)
idStr += Math.random().toString(36).substring(3)
return idStr
},
//封装组织结构 方法
convertChild(arr, parentItem, parentId){
parentItem.child = parentItem.child ? parentItem.child : [];
arr.forEach((item) => {
if (item.parent_id === parentId) {
parentItem.child.push(item);
this.convertChild(arr, item, item.id);
}
});
return parentItem.child;
},
convert(data, parentId) {
let convertData = [];
//这里需要转换成数组 请求回来的是对象
data=JSON.parse(JSON.stringify(data))
//forEach 是循环数组
data.forEach((item, index) => {
if (item.parent_id === parentId) {
convertData.push(item);
this.convertChild(data, item, item.id);
}
});
return convertData;
},
};
调用
async getStructureList(){
let { ctx, app } = this;
// 参数验证
ctx.validate({
page: { type: 'int', required: true, desc: '页码' }
})
let page =ctx.params.page
// 参数验证
let row = await app.model.Structure.findAll({
order: [
['order', 'ASC'] //DESC从大到小排序 ASC从小到大排序
],
});
let data={}
data.list=app.convert(row, 0)
data.totalCount=row.length
ctx.apiSuccess(data);
}
表结构
// app/model/structure.js
module.exports = app => {
const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;
const Structure = app.model.define('structure', {
id: { type: INTEGER(10), primaryKey: true, autoIncrement: true, unique: true },
parent_id: { type: INTEGER(10), allowNull: false, defaultValue: 0, comment: '上级菜单ID' },
name: { type: STRING(10), allowNull: false, defaultValue: '', comment: '菜单/权限名称' },
status:{ type: INTEGER(10), allowNull: false, defaultValue: 1, comment: '是否启用,0否1是' },
order:{ type: INTEGER(10), allowNull: false, defaultValue: 1, comment: '排序' },
created_time: { type:DATE, get(){ return app.formatTime(this.getDataValue('created_time')) } },
updated_time: DATE,
});
return Structure;
};