灏天阁

Node/Koa2[41]: 修改用户信息接口

· Yin灏

统一文件信息

处理接口路由

src/routes/api/user.js

//...
const { changeInfo } = require("../../controller/user");
//...
const { loginCheck } = require("../../middlewares/loginChecks");
const userValidate = require("../../validator/user");
const { genValidator } = require("../../middlewares/validator");
// patch 更新数据
router.patch(
  "/changeInfo",
  loginCheck,
  // 验证用户信息中间件
  genValidator(userValidate),
  async (ctx, next) => {
    const { nickName, city, picture } = ctx.request.body;
    // controller
    ctx.body = await changeInfo(ctx, { nickName, city, picture });
  }
);
//...

controller 层处理

src/controller/user.js

//..
const { SuccessModel, ErrorModel } = require("../model/ResModel");
const { changeInfoFailInfo } = require("../model/ErrorInfo");
const { updateUser } = require("../services/user");
//...
async function changeInfo(ctx, { nickName, city, picture }) {
  const { userName } = ctx.session.userInfo;
  if (!nickName) {
    nickName = userName;
  }
  // services 层
  const result = await updateUser(
    {
      newNickName: nickName,
      newCity: city,
      newPicture: picture,
    },
    {
      userName,
    }
  );
  if (result) {
    Object.assign(ctx, session, userInfo, {
      nickName,
      city,
      picture,
    });
    return new SuccessModel();
  }
  return new ErrorModel(changeInfoFailInfo);
}

module.exports = {
  //...
  changeInfo,
};

services 层

src/services/user.js

//...
async function updateUser(
  { newPassword, newNickName, newPicture, newCity },
  { userName, password }
) {
  // 拼接修改内容
  const updateData = {};
  if (newPassword) {
    updateData.password = newPassword;
  }
  if (newNickName) {
    updateData.nickName = newNickName;
  }
  if (newPicture) {
    updateData.picture = newPicture;
  }
  if (newCity) {
    updateData.city = newCity;
  }
  // 拼接查询条件
  const whereData = {
    userName,
  };
  if (password) {
    whereData.password = password;
  }
  // 执行修改
  const result = await User.update(updateData, {
    where: whereData,
  });
  return result[0] > 0;
}
//...
module.exports = {
  //...
  updateUser,
};

- Book Lists -