TIL 07.10

박선우·2022년 7월 11일
0

로직 구현

목록 보기
3/4
post-thumbnail

오늘의 문제

  1. 닉네임 중복검사시 없는 닉네임인데도 사용중인 닉네임이라고 뜬다고 피드백 받음
  2. 마이프로필에서 닉네임 변경시 validator가 적용 되지 않는 문제 피드백 받음
  3. 기존에 이메일/닉네임 중복검사를 param으로 받았는데 url에 email이 있으면 보안상 안좋다고 해서 body로 받게 수정
  4. 마이프로필에서 중복된 닉네임이라고 했지만 수정 버튼 눌렀을때 수정이 되는 부분 피드백 받음

1. && 3. 닉네임 중복검사시 없는 닉네임인데도 사용중인 닉네임, 이메일/닉네임 중복검사를 param

  • 예를 들어 's3몬스터는좋아' 라는 닉네임을 쓴다고 가정 해보겠다.

  • 근데 여기서 문제는 's3몬스터' 라는 닉네임은 사용중인 닉네임 이라고 뜬다 뭐가 문제였을까?

  • Service 부분

// 이메일 || 닉네임 중복검사
const duplicate = async (id) => {
  return await User.findAll({
    where: {
      [Op.or]: {
        email: { [Op.like]: `%${id}%` },
        nickname: { [Op.like]: `%${id}%` },
      },
    },
  });
};
exports.duplicate = duplicate;
  • Sequelize 문법을 통한 like (%${id}%들어온 id값을 조회)
  • 's3몬스터는좋아' => 's3몬스터' 앞부분 부터 똑같아서 중복된 닉네임이라고 나오는 문제였다.
  • Controller 부분
  • 기존 로직
// 이메일 || 닉네임 중복검사
const duplicate = async (req, res, next) => {
  try {
    const { id } = req.params;
    const idcheck = await userService.duplicate(id);

    if (idcheck.length) {
      res.status(400).send({
        result: false,
      });
      return;
    }
    res.status(200).send({
      result: true,
    });
  } catch (error) {
    console.log(error);
    next(error);
  }
};
exports.duplicate = duplicate;
  • 변경된 로직
// 이메일 || 닉네임 중복검사
const duplicate = async (req, res, next) => {
  try {
    const id = req.body.email || req.body.nickname;
    const idcheck = await userService.duplicate(id);

    if (idcheck[0]?.email === id || idcheck[0]?.nickname === id) {
      res.status(400).send({
        result: false,
      });
      return;
    }
    res.status(200).send({
      result: true,
    });
  } catch (error) {
    console.log(error);
    next(error);
  }
};
exports.duplicate = duplicate;
  • 이러한 문제는 like %${id}%로 조회 했기 때문에 발생한 오류다. like는 id에 포함된 모든걸 조회 하기 때문이다
// 이메일 || 닉네임 중복검사
const duplicate = async (id) => {
  return await User.findAll({
    where: {
      [Op.or]: {
        email: id,
        nickname: id,
      },
    },
  });
};
exports.duplicate = duplicate;
  • 이렇게 변경하니 오류를 해결 할 수 있었다!

달라진점

  • 기존 param로 받던 부분 body로 받았고 거기에 따른 || 써서 email또는 nickname 을 id로 받아 구현함

  • if 조건문이 idcheck.length부분을 변경

  • 확실하게 비교하기 위해서, db에서 찾은 id값과 body값으로 받은 id 값이 일치 여부를 추가했다

2. && 4.마이프로필에서 닉네임 변경시 validator가 적용 되지 않는 문제, 중복된 닉네임이라고 했지만 수정 버튼 눌렀을때 수정이 되는 부분

Controller 부분

  • 기존 로직
// 마이프로필 수정
const myprofile_correction = async (req, res, next) => {
  try {
    const { user } = res.locals;
    const profileImage = req.file?.transforms[0].key;
    const { nickname, introduction } = req.body;

    const profileimg = await userService.myprofile_correction(
      user,
      profileImage,
      nickname,
      introduction
    );

    res.status(200).send(profileimg);
  } catch (error) {
    console.log(error);
    next(error);
  }
};
exports.myprofile_correction = myprofile_correction;
  • 변경된 로직
// 마이프로필 수정
const myprofile_correction = async (req, res, next) => {
  try {
    const { user } = res.locals;
    const profileImage = req.file?.transforms[0].key;
    const { nickname, introduction } = req.body;

    // 닉네임 안에 정규식이 포함 되어 있으면 true, 없으면 false
    const nickname_validator = /^[-|-|a-z|A-Z|0-9]+$/.test(nickname);

    // 닉네임 유효성 검사
    if (3 > nickname.length || nickname.length > 15) {
      return res
        .status(400)
        .send({ ValidationError: '3글자 ~ 15글자 이내로 작성해주세요' });
    } else if (!nickname_validator) {
      return res
        .status(400)
        .send({ ValidationError: '한글,숫자, 알파벳 대소문자로 입력해주세요' });
    }

    const profileimg = await userService.myprofile_correction(
      user,
      profileImage,
      nickname,
      introduction
    );

    if (profileimg === false) {
      return res.status(400).send({
        result: false,
      });
    }

    res.status(200).send(profileimg);
  } catch (error) {
    console.log(error);
    next(error);
  }
};
exports.myprofile_correction = myprofile_correction;

Service 부분

  • 기존 로직
// 마이 프로필 수정
const myprofile_correction = async (user, profileImage, nickname, introduction) => {
  await deleteImg(user.profileImage);

  await User.update(
    { profileImage, nickname, introduction },
    { where: { userId: user.userId } }
  );
  • 변경된 로직
const myprofile_correction = async (user, profileImage, nickname, introduction) => {
  const duplicate = await User.findAll({
    where: { nickname },
  });

  // 닉네임 중복 체크
  if (duplicate.length) {
    return false;
  }

  await deleteImg(user.profileImage);

  await User.update(
    { profileImage, nickname, introduction },
    { where: { userId: user.userId } }
  );
  • joi를 써서 validator를 진행 하고 싶었으나 마이프로필 변경이라 기존 꺼를 가져다 쓰기엔 required()이 설정되 있어서 포기

  • joi 스키마를 만들어서 진행할까 하다가 포기

  • pacth로 데이터를 전달 받기때문에 nickname 하나 검사하자고 스키마하나를 만드는건 너무 비효율 적이라고? 생각해서 포기했음

  • Service 부분에서 nickname 중복검사 한뒤 있으면 false 반환하고

  • Controller 부분에서 false를 받아왔을때 false를 결과값으로 줌

profile
코린이 열심히 배우자!

0개의 댓글