Giter VIP home page Giter VIP logo

tindater-backend's Introduction

Tindater

  • Service Demostration

틴데이터 시연영상

  • Tinder Clone coding team projects

Team members

image

Directory Structure

root
├─config
├─docs
├─layers
│  ├─controllers
│  ├─repositories
│  ├─routers
│  └─services
├─middlewares
├─migrations
├─models
├─modules
├─node_modules
└─seeders

Packages

  "dependencies": {
    "aws-sdk": "^2.1201.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "joi": "^17.6.0",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0",
    "mysql2": "^2.3.3",
    "nodemon": "^2.0.19",
    "sequelize": "^6.21.4",
    "sequelize-cli": "^6.4.1"
  },
  "devDependencies": {
    "jest": "^28.1.3"
  }

tindater-backend's People

Contributors

codeing999 avatar minsun91 avatar jeonjiw avatar

Forkers

minsun91

tindater-backend's Issues

테이블에 외래키 생성 안되는 문제

문제 :
아래와 같은 방법으로 저번주차에 외래키 생성은 물론이고 cascade까지 적용되는 것을
워크벤치로 확인했었는데 이번 클론주차에서는 먹히지 않는다.

//user를 참조하는 테이블의 모델 파일
LikeAndDislike.associate = function (models) {
    LikeAndDislike.belongsTo(models.User, {
      foreignKey: "userId",
      targetKey: "userId",
      onUpdate: "cascade",
      onDelete: "cascade",
      constraints: false,
    });
    LikeAndDislike.belongsTo(models.User, {
      foreignKey: "targetUserId",
      targetKey: "userId",
      onUpdate: "cascade",
      onDelete: "cascade",
      constraints: false,
    });
  };
//user 모델 파일
 User.associate = function (models) {
    User.hasMany(models.LikeAndDislike, {
      foreignKey: "userId",
      sourceKey: "userId",
      onUpdate: "cascade",
      onDelete: "cascade",
      constraints: false,
    });
    User.hasMany(models.LikeAndDislike, {
      foreignKey: "targetUserId",
      sourceKey: "userId",
      onUpdate: "cascade",
      onDelete: "cascade",
      constraints: false,
    });
  };

Bug : ec2 instance로 배포 시, pull 안되는 문제

git pull origin submain
fatal: unsafe repository ('/home/ubuntu/TinDater-backend' is owned by someone else)
To add an exception for this directory, call:

    git config --global --add safe.directory /home/ubuntu/TinDater-backend

clone은 잘 돼었는데, unsafe한 repository라는 이유로 pull이 안되는 문제.

Bug : sequelize cannot add or update a child row a foreign key constraint fails

likes와 dislikes 테이블에 새 로우를 추가하려고할 때 이와 같은 에러가 뜨면서 추가되지 않는다.

sequelize cannot add or update a child row a foreign key constraint fails

에러 문구를 보니, 외래키 관계는 연결되어 있어서 이런 문제가 발생하는 것 같은데,
여기서 또 무엇을 해줘야 child row에 추가가 될지 모르겠다.

Likes 테이블과 Dislikes 테이블을 LikeAndDislikes 테이블로 병합.

#28

ERD 변경

변경 전

image

변경 후

image

개선점

const dislikepeople = await Dislike.findAll({
        attributes: ["dislikeUserId"],
        where: { userId: userId },
        raw: true,
      });
      let dislikeset = new Set();
      dislikepeople.map((data) => dislikeset.add(data.dislikeUserId));
//생략
	  dislikeset.forEach((v) => peopleset.delete(v));

테이블 두개로 연산해야할 이런 부분이 한번으로 축소되었다.

마이그래이션 파일 삭제, 좋아요한 사용자 목록 조회 쿼리 개선

#38

  1. 마이그래이션 파일 삭제
sequelize
  .sync({ force: true })
  .then(() => {
    console.log("db connect seccess");
  })
  .catch((err) => {
    console.error(err);
  });

이 sync 기능을 이용하면 별도의 마이그래이션이 없이도 모델 파일들 만으로도 테이블이 생성됨을 알게 되었습니다.
그동안 마이그래이션의 불편함을 알면서도 어쩔 수 없이 사용해왔지만 이제 불필요하여 삭제합니다.

  1. 좋아요한 사용자 목록 조회 쿼리 개선
    좀 더 익숙해진 문법을 적용하여 쿼리를 개선해 보았습니다.

개선 전 :

//로그인한 유저의 userId가 좋아요한 likeUserId의 배열
      const people = await LikeAndDislike.findAll({
        where: {
          userId: userId,
          isLike: true,
        },
        attributes: ["targetUserId"],

        raw: true,
      });

      let userList = [];

      //내가 좋아요 누른 그사람들도 날 좋아하는지
      for (let i in people) {
        const likeUserId = people[i].targetUserId;
        const userInfo = await User.findOne({
          where: { userId: likeUserId },
          raw: true,
        });
        const isLikeMe = await this.getIsLikeMe(userId, likeUserId);
        //userList.push(userInfo);
        userList[i] = {
          userId: userInfo.userId,
          email: userInfo.email,
          nickname: userInfo.nickname,
          age: userInfo.age,
          address: userInfo.address,
          gender: userInfo.gender ? true : false,
          imageUrl: userInfo.imageUrl,
          interest: userInfo.interest.split(""),
          likeMe: isLikeMe.isLikeMe,
          x: userInfo.x,
          y: userInfo.y,
        };
      }

개선 후 :

const people = await LikeAndDislike.findAll({
        where: { userId, isLike: true },
        //as: "subjectUser",
        attributes: [],
        include: [
          {
            model: User,
            as: "objectUser",
          },
        ],
        raw: true,
      });

      const result = people.map((v) => {
        return {
          userId: v["objectUser.userId"],
          email: v["objectUser.email"],
          nickname: v["objectUser.nickname"],
          age: v["objectUser.age"],
          address: v["objectUser.address"],
          gender: v["objectUser.gender"],
          imageUrl: v["objectUser.imageUrl"],
          interest: v["objectUser.interest"].split(""),
          x: v["objectUser.x"],
          y: v["objectUser.y"],
        };
      });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.