• 로그인을 하여 부여받은 jwt token은 일단 쿠키에 저장
    • 문제 : 동시에 100명이 접속해 있으면 이걸 어떻게 처리하지??
      아!! 각 유저의 브라우저에 있는 쿠키니까 상관이 없네;;

 

게시물 게시

토근이 있으면 유저의 아이디를 알 수 있으니 게시물을 누가 게시했는지 표기는 가능

토큰발급 받아서 쿠키에 저장 -> 미들웨어 authenticateToken.js 에서 쿠키 사용 

router.post('/sign-in', async (req, res, next) => {
  try {
    const { email, password } = req.body;
    await sequelize.transaction(async () => {
      // code..
      res.cookie('token', accessToken).status(200).send('로그인에 성공하였습니다.');
    });
  } catch (err) {
    next(err);
  }
});

 

//미들웨어에서
const token = req.cookies['token'];

 

<문제> 크롬에서 서드파티 쿠키를 곧 사용할 수가 없게 된다는 뉴스

 

다른 방식시도가 필요!!

 

 

지하철에 있는 보관함의 위치를 지도에서 보여주고 앱의 작은 부분 구현해보기

 

  1. 로그인/로그아웃
  2. 질문을 올릴 수 있는 게시판 -로그인 시에만 가능
  3. 질문에 댓글게시
  4. 사물함 상태 표시 (사용중, 점검중, 선택가능)
  5. 역 위치 지도에 표시 - 좌표만 전달
  6. 역 별 날씨상태표시 - weather API 이용
  7. 역 별 주소 표시

Post 는 해당 pk 로 전부 지워지는데 comment는 postId 부분만 지워진다.

 

>> 지우는 순서의 문제다!!

router.delete('/:id', async (req, res) => {
    const id = req.params.id;
    await sequelize.transaction(async ()=>{
        
        await Post.destroy({where: {id: id}}); // 1
        await Comment.destroy({where: {postId: id}}); // 2
    })
    res.status(204).send();
})

여기서 1 이 지워지면  Comment에 있는 postId가 어디를 참조 하고 있는지 몰라서 NULL로 바뀌고

2 의 코드에서 지워야할 포스트를 찾을 수가 없으므로 코멘트가 지워지지 않는다.

 

!! 각 모델에서 foreignKey가 어떤 모델과 관계가 있는 지 꼭 확인을 하고 지우는 순서를 고려해야 한다.

router.delete('/:id', async (req, res) => {
    const id = req.params.id;
    await sequelize.transaction(async ()=>{
        await Comment.destroy({where: {postId: id}}); // 1
        await Post.destroy({where: {id: id}}); // 2
        
    })
    res.status(204).send();
})
.../routers/posts.js:65
allPosts.sort(sortDateDescending);
TypeError: allPosts.sort is not a function

이유가 뭐지?? allPosts가 array가 아닌가?? -> console 로 출력 해보자

 

<시도>

const allPosts = Post.findAll();
console.log(allPosts);
console.log(Array.isArray(allPosts);

 

<결과>

// console.log(allPosts)의 출력 결과
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 1230,
  [Symbol(trigger_async_id_symbol)]: 1222
}

// console.log(Array.isArray(allPosts))의 출력 결과
false

TypeError: allPosts.sort is not a function

 

>>  첫번째 출력은 뭔지 모르겠으나, Array 형식이 아니라고 하여 형식을 변환 후 출력

const allPosts = Post.findAll();
const allPostsArray = Array.from(allPosts)

console.log(allPostsArray);  // 출력 : []
console.log(Array.isArray(allPostsArray));// 출력: true

 

<< 코드는 정상적으로 작동하는데 받아오는 값이 없다>>

  1. Sequelize 에서 findAll 조사 : https://sequelize.org/api/v6/class/src/model.js~model#static-method-findAll.

..... 문제는 단순했다...   await 를 쓰지 않은 상태에서  array 형태로 변형 시켜서 allPosts 에 아무런 값이 담기지 않았다.

//const allPosts = Post.findAll(); 
const allPosts = await Post.findAll();
 

에러 메세지

#입력값
{ title: 'test posting4', content: 'nothing', categoryId: 1, hashtag: 'test' }

Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): START TRANSACTION;
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): SELECT `id`, `word`, `created_at` AS `createdAt`, `updated_at` AS `updatedAt` FROM `hashtags` AS `hashtags` WHERE `hashtags`.`word` = 'test' LIMIT 1;
null
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): INSERT INTO `hashtags` (`id`,`word`,`created_at`,`updated_at`) VALUES (DEFAULT,?,?,?);
Executing (95522a76-98e3-47e9-9e38-97e9a7db1ed0): ROLLBACK;

# 실패한 쿼리 (Error 메세지에서 )
at async posts.create (/Users/joey/WebstormProjects/practice_DB_ORM_API/node_modules/sequelize/lib/model.js:1362:12) { sql: 'INSERT INTO `posts` (`id`,`title`,`content`,`created_at`,`updated_at`,`category_id`) VALUES (DEFAULT,?,?,?,?,?);' }

<추측>

1. 아마도 카테고리가 이미 생성되지 않은 상태에서  categoryId를 주어서 그럴까?

-> category를 먼저생성해서 확인 절차 코드를 추가하기 (이 부분에서 에러가 발생한 것이 맞다.)

 

<해결>

1. category를 먼저 생성

- 이 부분에서 저번에 했던 실수가 반복됨 : body 에서 { "category": "IT"}를 전달했는데 키를 동일하게 입력하지 않아서 오류 또 발생

const {newCategory } = req.body;

 

2. post를 게시(Post)할 때 category에 존재하는 id를 넘겨 줄것. 

 

* 추가적으로 transaction 에서 데이터와 관련된 작업을 순차적으로 진행되도록 관련된 코드앞에 await를 꼭 붙일 것

// 여기에서 await를 넣지 않음
const post = await Post.create(...)

 

>>> 내가 Post-Category 간의 관계를 설정해 두어서 새로운 Post를 생성할 때 Sequelize 에서 자동으로 주어진 categoryId 가 존재하는지 확인과정을 거쳤고, 그 결과 임의로 준 categoryId 가  Category에 존재하지 않아서 에러를 발생함. 

# 에러를 찾다가 발견한 것들

< 두 개의 table 을 연결해주는 모델을 만들때 좀더 명확하게 하는 것이 좋다.>

const PostHashtag = sequelize.define('post_hashtag', {
    id :{
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    postId:{
        type: DataTypes.INTEGER,
        // 명확하게 하기 위해 추가된 코드
        references:{
            model:'posts',
            key: 'id'
        }
    },
    hashtagId:{
        type: DataTypes.INTEGER,
        // 명확하게 하기 위해 추가된 코드
        references: {
            model:'hashtags',
            key:'id'
        }
    },
},{
    underscored:true
})

 

< transaction 내에서 수행한 각 쿼리의 결과를 수행하고 나면 꼭 해당 메서드를 트랜잭션에 보내서 오류가 발생하는지 파악하기>

// 예를 들어서 { transaction: t } 을 추가
const post = await Post.create({
    title,
    content,
    createdAt: new Date(),
    categoryId
    }, { transaction: t }
);
            
await post.addHashtag(existingHashtag, { transaction: t });

 

<아래의 코드 한 줄로 Post 와 Hash의 관계를 설정해주기 위해 만든 PostHashtag 에 자동으로 입력되는 것이 신기하다. >

await post.addHashtag(existingHashtag, {transaction:t});

+ Recent posts