본문 바로가기

Project/TIL

20.03.19 ShareBook TIL

유저와 책 테이블에서 한 명의 유저는 여러 가지의 책을 등록할 수 있다 생각해서 일대다 관계를 설정했다고 생각했는데 막상 포스트맨으로 날려보니 유저 아이디가 들어가지 않았다.

const token = req.cookies.data;
    const decoded = jwt.verify(token, String(process.env.JWT_SECRET));
    try {
      if (decoded) {
        // console.log(decoded);
        await Books.create({
          name: name,
          publisher: publisher,
          writer: writer,
          quelity: quelity,
          description: description,
          image: image,
          isRental: isRental,
          bookRegion: bookRegion,
        })
          .then(result => {
            if (result) res.json(result);
          })
          .catch(error => {
            console.log(error);
            res.sendStatus(500);
          });
      }

 

알고보니 Books table에 데이터를 생성할 때 외래키로 지정해준 userOwnerId를 넣고 있지 않았다.

 

userOwnerId: decoded.id, 

 

코드를 넣어 주니 .id에서 type에러가 났다.

왜그런지 한참을 찾아보다가 decoded는 타입을 지정해 주지 않아서 .id같은건 사용할 수가 없었다.

console로 decoded를 찍어보니 객체형식이여서 Object로 설정해 주었지만 여전히 동작하지 않았다.

결국 type을 any로 설정해주어서야 사용할 수가 있었다.

const token = req.cookies.data;
    const decoded: any = jwt.verify(token, String(process.env.JWT_SECRET));
    try {
      if (decoded) {
        // console.log(decoded);
        await Books.create({
          name: name,
          publisher: publisher,
          writer: writer,
          quelity: quelity,
          description: description,
          image: image,
          isRental: isRental,
          bookRegion: bookRegion,
        })
          .then(result => {
            if (result) res.json(result);
          })
          .catch(error => {
            console.log(error);
            res.sendStatus(500);
          });
      }

 

내 지역에서 대여 가능한 책 리스트를 불러오는 함수를 작성하였다.

처음에는 어떻게 내 지역 정보와 Books.bookRegion를 비교하여 테이터를 불러올까에 대해 생각해보았다.

생각의 흐름 

  1. 유저의 id 필요
  2. 토큰에 유저의 id가 담겨 있으므로 그걸 이용하여 찾아보자
  3. 해당 id 유저의 정보를 가져와 bookRegion에 유저의 region을 넣어 주자
import { Request, Response, NextFunction } from 'express';
import { Books } from '../../../models/Books';
import { Users } from '../../../models/Users';
import jwt from 'jsonwebtoken';

const jwtSecret = String(process.env.JWT_SECRET);

module.exports = {
  get: async (req: Request, res: Response) => {
    const token = req.cookies.data;
    const decode: any = jwt.verify(token, jwtSecret);
    try {
      if (decode) {
        await Users.findOne({
          where: {
            id: decode.id,
          },
        }).then(data => { // 해당 유저 정보를 data에 담아준다
          const user: any = data; // data의 타입을 지정해 준다
          Books.findAll({
            where: {
              isRental: '대여 가능',
              bookRegion: `${user.region}`, // 타입이 문자이므로 ``을 사용하여 문자열로 변형
            },
          }).then(result => {
            // console.log(result);
            res.json(result);
          });
        });
      } else {
        res.send('해당 지역에 대여 가능 도서가 존재하지 않습니다');
      }
    } catch (err) {
      console.error(err);
      res.status(500).send('Server Error');
    }
  },
};

 

 

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

20.03.21 ShareBook TIL  (0) 2020.03.22
20.03.20 ShareBook TIL  (0) 2020.03.20
20.03.18 ShareBook TIL  (0) 2020.03.19
20.03.17 ShareBook TIL  (0) 2020.03.18
20.03.16 ShareBook TIL  (0) 2020.03.17