install.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const path = require('path');
  7. //
  8. class InstallService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'install');
  11. this.dataIndex = path.resolve('app', 'public', 'defaultData');
  12. }
  13. async init() {
  14. await this.initRole();
  15. await this.initAdmin();
  16. await this.initTestBasic();
  17. }
  18. /**
  19. * 初始化角色数据
  20. */
  21. async initRole() {
  22. const model = this.ctx.model.System.Role;
  23. const num = await model.count();
  24. if (num > 0) return;
  25. const dataPath = path.resolve(this.dataIndex, 'role.js');
  26. const list = require(dataPath);
  27. await model.insertMany(list);
  28. }
  29. /**
  30. * 初始化管理员
  31. */
  32. async initAdmin() {
  33. const model = this.ctx.model.System.User;
  34. const roleModel = this.ctx.model.System.Role;
  35. const num = await model.count();
  36. if (num > 0) return;
  37. // 需要将role中menu的mode为all的数据取出来,这是超级管理员的角色信息
  38. const roleData = await roleModel.findOne({ code: 'sadmin' });
  39. if (!roleData) return;
  40. const { _id: role } = roleData;
  41. const dataPath = path.resolve(this.dataIndex, 'user.js');
  42. let list = require(dataPath);
  43. list = list.map(i => ({ ...i, role }));
  44. await model.insertMany(list);
  45. }
  46. /**
  47. * 初始化测试用户
  48. */
  49. async initTestBasic() {
  50. const model = this.ctx.model.Basic;
  51. const roleModel = this.ctx.model.System.Role;
  52. const userModel = this.ctx.model.System.User;
  53. const num = await model.count();
  54. if (num > 0) return;
  55. const roleData = await roleModel.findOne({ code: 'user' });
  56. if (!roleData) return;
  57. const { _id: role } = roleData;
  58. const dataPath = path.resolve(this.dataIndex, 'basic.js');
  59. const list = require(dataPath);
  60. const basicList = await model.insertMany(list);
  61. const users = basicList.map(i => {
  62. const { _id: basic, name, phone } = i;
  63. const obj = { role, basic, phone, name, account: name, password: { secret: '111111' } };
  64. return obj;
  65. });
  66. await userModel.insertMany(users);
  67. }
  68. }
  69. module.exports = InstallService;