20210210 TIL 비동기

2021. 2. 11. 08:51·BootCamp_Codestates/TIL

 

회원 탈퇴 기능 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/

'BootCamp_Codestates > TIL' 카테고리의 다른 글

20210317 Job searching Sprint 2일차  (0) 2021.03.19
20210317 Job searching Sprint 1일차  (0) 2021.03.18
20210205 TIL  (0) 2021.02.05
20210203 TIL  (0) 2021.02.04
20210127-30  (0) 2021.01.31
'BootCamp_Codestates/TIL' 카테고리의 다른 글
  • 20210317 Job searching Sprint 2일차
  • 20210317 Job searching Sprint 1일차
  • 20210205 TIL
  • 20210203 TIL
JTB
JTB
웹/앱 개발 정보를 공유하고 있습니다.
  • JTB
    JTechBlog
    JTB
  • 전체
    오늘
    어제
    • All About Programming;)
      • Computer Science
        • Terminology and Concepts
        • Network
        • Operating System
        • Database
        • Data Structure
        • Web Development
      • Frontend
        • Javascript Essentials
        • Perfomance Optimization
        • JS Patterns
        • React
        • Next.js
        • Flutter
        • Testing
      • Backend
        • Node.js
      • DevOps
        • Docker & Kubernetes
      • Coding Test
        • LeetCode
        • Programmers
      • Tech Books & Lectures
        • Javascript_Modern JS Deep d..
        • Network_IT 엔지니어를 위한 네트워크 입문
      • Projects
        • PolyLingo_2025
        • Build Your Body_2024
        • JStargram_2021
        • Covid19 Tracker_2021
        • JPortfolio_2021
      • BootCamp_Codestates
        • TIL
        • TILookCloser
        • Pre Tech Blog
        • IM Tech Blog
        • Daily Issues and DeBugging
        • First Project
        • Final Project
        • Sprint Review
        • Good to Know
        • Socrative Review
        • HTML & CSS
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 글쓰기
    • 관리
  • 공지사항

  • 인기 글

  • 태그

    자바스크립트 딥다이브
    스코프
    Binary Tree BFS
    database
    프론트엔드 성능 최적화 가이드
    모던 자바스크립트 Deep Dive
    js pattern
    How memory manage data
    Javascript Essentials
    indie hacker
    polylingo
    Time complexity and Space complexity
    VoiceJournal
    structure of os
    CPU scheduling algorithm
    leetcode
    DOM
    mobile app
    딥다이브
    Threads and Multithreading
    Shared resources
    Network
    이벤트
    need a database
    Operating System
    자바스크립트
    커리어
    Data Structure
    testing
    TCP/IP
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
20210210 TIL 비동기
상단으로

티스토리툴바