user.js 1.09 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// app/service/user.js
const Service = require('egg').Service;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserService extends Service {
  async update(body, _this) {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const user = await ctx.model.User.findByPk(decode?.id);
    if (!user) {
      ctx.status = 404;
      _this.fail('库里没有该条数据');
      return;
    }
    await user.update(body);
    _this.success(user);
    return user;
  }

  async getcurrentuser() {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const result = await ctx.model.User.findByPk(toInt(decode.id));
    let orginfo = {};
    if (result?.org_id) {
      orginfo = await ctx.model.Org.findByPk(toInt(result?.org_id));
    }
    return { ...orginfo.dataValues, ...result.dataValues };
  }
}

module.exports = UserService;