TIL 23-06-20

level·2023년 6월 20일

TIL

목록 보기
32/95

(Authorization ?? "").split(" ");

??: 널 병합 연산자
authorization 변수가 undefined이거나 null 값일 경우 빈 문자열("")로 변경
.split(" ") : bearer 과 token 분리

res.locals.user = user;

사용자 정보를 express가 제공하는 안전한 변수에 담아두기

jwt.sign/verify 에서 입력한 시그니처키 일치하도록 주의할 것

find(category ? { category } : {})

Query Param으로 category 가 전달되었을 경우 해당하는 category로 조회하고, category가 존재하지 않을 경우 모든 상품을 조회

AUTO_INCREMENT

데이터 삽입 시 데이터가 없어도 고유한 값을 유지할 수 있도록 하는 속성

attributes

출력할 컬럼만 지정하기

const post = await Posts.findOne({
    attributes: ["postId", "title", "content", "createdAt", "updatedAt"],
    where: { postId }
  });

where 속성에 Op

where: {
        [Op.and]: [{ postId }, [{ password }]],
      }

OR(||), AND(&&), LIKE, 정규표현식 등 다양한 연산자를 사용할 수 있게함

migration 작성 시 테이블간의 관계

1:N 관계

//migrations/생성날짜-create-users.js
 userId: {
        allowNull: false, // NOT NULL
        autoIncrement: true, // AUTO_INCREMENT
        primaryKey: true, // Primary Key (기본키)
        type: Sequelize.INTEGER
      },
// migrations/생성날짜-create-posts.js
UserId: {
        allowNull: false, // NOT NULL
        type: Sequelize.INTEGER,
        references: {
          model: 'Users', // Users 모델을 참조합니다.
          key: 'userId', // Users 모델의 userId를 참조합니다.
        },
        onDelete: 'CASCADE', // 만약 Users 모델의 userId가 삭제되면, Posts 모델의 데이터가 삭제됩니다.
      },

1:1 관계

//migrations/생성날짜-create-user-infos.js
UserId: {
        allowNull: false, // NOT NULL
        type: Sequelize.INTEGER,
        unique: true, // UNIQUE
        references: {
          model: 'Users', // Users 모델을 참조합니다.
          key: 'userId', // Users 모델의 userId를 참조합니다.
        },
        onDelete: 'CASCADE', // 만약 Users 모델의 userId가 삭제되면, UserInfos 모델의 데이터가 삭제됩니다.
      },

model을 이용해 테이블 설계를 하게 되었을 경우 문제

1) Sequelize의 model 설계 변경 시 현재 서비스중인 테이블 삭제 된 후 생성 (정보 유실)

2) MySQL의 테이블이 Node.js Application에 의존적 (현재 DB의 상황을 인지하기 힘들어지고, MySQL에 직접 등록한 부가적인 기능들을 이해하기 힘듬)

Sequelize의 include 문법

Users.findOne({
  attributes: ["userId", "email", "createdAt", "updatedAt"],
  include: [
    {
      model: UserInfos,
      attributes: ["name", "age", "gender", "profileImage"],
    }
  ],
  where: { userId }
});

SQL의 JOIN과 동일한 역할
model에서 hasMany, hasOne, BelongsTo와 같이 관계 설정이 되어야 현재 모델에서 참조하는 외래 키를 인식하고, SQL을 생성할 수 있음

0개의 댓글