BootCamp_Codestates/TIL

20210210 TIL 비동기

Nomad Kim 2021. 2. 11. 08:51

 

회원 탈퇴 기능 API 구현(duser)

const { user, content, image, comment } = require('../../models');
const { isAuthorized } = require('../tokenFunctions');
const { refreshToken } = require('../tokenFunctions/refreshtokenrequest');

module.exports = {
  delete: async (req, res) => {
    //TODO: 유저 회원탈퇴 로직
    const accessTokenData = isAuthorized(req);
    if (!accessTokenData) {
      refreshToken(req, res);
    } else {
      const userId = accessTokenData.id;

      //지워야할 데이터? 1. 유저 2. 모든 컨텐츠 3. 모든 이미지 4. 모든 댓글
      //! 1. 유저 데이터 삭제
      await user.destroy({
        where: { id: userId },
      });
      // user.destroy => 삭제된 갯수를 return 한다. 즉, 찾으면 삭제한다.

      const findContents = await content.findAll({
        where: { userId: userId },
        attributes: ['id'],
      });
      let contentIdArray = findContents.map(content => content.dataValues.id);

      //! 2. 모든 이미지 삭제(content id 필요)
      await image.destroy({
        where: { contentId: contentIdArray },
      });
      //! 3. 모든 댓글 삭제(content id 필요)
      await comment.destroy({
        where: { contentId: contentIdArray },
      });
      //! 4. 마지막으로 모든 컨텐츠 데이터 삭제.
      await content.destroy({
        where: { userId: userId },
      });
      return res.status(200).send('deleted user information successfully');
    }
    return res.status(500).send('err');
  },
};

 

모든 이미지 삭제(2) 와 모든 댓글 삭제(3) 할 때 컨텐츠 데이터에 종속되는 다대일 관계이므로 content id 가 필요하다.

따라서 모든 컨텐츠 데이터 삭제(4) 하기전에 findContents 를 통해 모든 컨텐츠의 아이디 값(PK) 을 구해놓는 것이 포인트이다.

 

회원 정보 업데이트 API 구현(uuserinfo)

const { user } = require('../../models');
const { isAuthorized } = require('../tokenFunctions');
const { refreshToken } = require('../tokenFunctions/refreshtokenrequest');
const crypto = require('crypto');
require('dotenv').config();

module.exports = {
  patch: async (req, res) => {
    //TODO: 유저정보 업데이트 로직 작성

    const accessTokenData = isAuthorized(req);
    if (!accessTokenData) {
      refreshToken(req, res);
    } else if (accessTokenData) {
      const { password, mobile, avatar } = req.body;

      const isUpdated = async () => {
        if (password) {
          const encrypted = crypto
            .pbkdf2Sync(
              password,
              process.env.DATABASE_SALT,
              100000,
              64,
              'sha512',
            )
            .toString('base64');
          return user.update(
            {
              password: encrypted,
              updatedAt: new Date(),
            },
            {
              where: { id: accessTokenData.id },
            },
          );
        } else if (mobile) {
          return user.update(
            {
              mobile: mobile,
              updatedAt: new Date(),
            },
            {
              where: { id: accessTokenData.id },
            },
          );
        } else if (avatar) {
          return user.update(
            {
              avatar_url: avatar,
              updatedAt: new Date(),
            },
            {
              where: { id: accessTokenData.id },
            },
          );
        }
      };

      const isUpdatedResult = await isUpdated();

      if (!isUpdatedResult) {
        res.status(404).send('result not found');
      }
      const returnedUpdatedUserinfo = await user.findOne({
        where: { id: accessTokenData.id },
      });
      delete returnedUpdatedUserinfo.dataValues.password;
      return res.status(200).json({
        data: { userInfo: returnedUpdatedUserinfo.dataValues },
        message: 'ok',
      });
    }
    res.status(500).send('err');
  },
};

데이터를 처리하는데에 시간이 걸릴 수 있기 때문에 비동기 처리가 포인트이다.

비밀번호, 모바일, 아바타 업데이트 요청에 따라 if 구문으로 분기하여 처리한다.

 

참고한 자료

출처: www.daleseo.com/js-async-async-await/