user.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class UserService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.User;
  8. }
  9. async create({ name, thumbnail, phone, company, tab, openid }) {
  10. assert(name, '昵称不存在');
  11. assert(phone, '电话不存在');
  12. assert(openid, 'openid不存在');
  13. const filter = {};
  14. const arr = { phone, openid };
  15. for (const e in arr) {
  16. const data = `{ "${e}": "${arr[e]}" }`;
  17. if (arr[e]) {
  18. filter.$or = [];
  19. filter.$or.push(JSON.parse(data));
  20. }
  21. }
  22. const total = await this.model.find({ ...filter });
  23. if (total.length > 0) {
  24. return { errcode: -1001, errmsg: '手机号或微信已存在' };
  25. }
  26. try {
  27. const res = await this.model.create({ name, thumbnail, phone, company, tab, openid });
  28. return { errcode: 0, errmsg: 'ok', data: res };
  29. } catch (error) {
  30. throw error;
  31. }
  32. }
  33. async update({ id, name, thumbnail, phone, company, tab, openid }) {
  34. assert(id, 'id不存在');
  35. try {
  36. await this.model.updateOne({ _id: id }, { name, thumbnail, phone, company, tab, openid });
  37. return { errcode: 0, errmsg: 'ok', data: '' };
  38. } catch (error) {
  39. throw error;
  40. }
  41. }
  42. async delete({ id }) {
  43. assert(id, 'id不存在');
  44. try {
  45. await this.model.deleteOne({ _id: id });
  46. return { errcode: 0, errmsg: 'ok', data: '' };
  47. } catch (error) {
  48. throw error;
  49. }
  50. }
  51. async query({ skip, limit, name, phone, company, tab, openid }) {
  52. const filter = {};
  53. const arr = { name, phone, company, tab, openid };
  54. for (const e in arr) {
  55. const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
  56. if (arr[e]) {
  57. filter.$or = [];
  58. filter.$or.push(JSON.parse(data));
  59. }
  60. }
  61. try {
  62. const total = await this.model.find({ ...filter });
  63. let res;
  64. if (skip && limit) {
  65. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  66. } else {
  67. res = await this.model.find({ ...filter });
  68. }
  69. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  70. } catch (error) {
  71. throw error;
  72. }
  73. }
  74. }
  75. module.exports = UserService;