user.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. //
  7. class UserService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'user');
  10. this.mysql = this.ctx.service.mysql;
  11. this.userRelation = this.ctx.model.UserRelation;
  12. }
  13. async query({ superior_id, ...others }, { skip = 0, limit = 0 } = {}) {
  14. assert(superior_id, '缺少查询信息');
  15. // 通过上级id找关系
  16. const relation = await this.userRelation.find({ superior_id }).skip(parseInt(skip)).limit(parseInt(limit));
  17. const total = await this.userRelation.count({ superior_id });
  18. // 确定好是哪些用户,然后拿id换用户信息
  19. const ids = relation.map(i => i.user_id);
  20. if (ids.length <= 0) return { data: [], total };
  21. const table = 'sys_user';
  22. let { data } = await this.mysql.query(table, { user_id: ids, ...others });
  23. data = data.map(i => _.omit(i, [ 'password' ]));
  24. // 将key转换成java部分的驼峰显示
  25. data = data.map(i => {
  26. const keys = Object.keys(i);
  27. const newObject = {};
  28. for (const key of keys) {
  29. const value = i[key];
  30. const newKey = _.camelCase(key);
  31. newObject[newKey] = value;
  32. }
  33. return newObject;
  34. });
  35. return { data, total };
  36. }
  37. // 创建上下级用户关系
  38. async create(body) {
  39. const data = await this.userRelation.create(body);
  40. return data;
  41. }
  42. // 删除上下级用户关系
  43. async delete({ id }) {
  44. const result = await this.userRelation.deleteOne({ user_id: id });
  45. return result;
  46. }
  47. }
  48. module.exports = UserService;