Wecode - Project 1 (부트캠프)/Project 1 과정

Project 1- 3일차 : 코드 리뷰, 비교 - threadService / 포스트 Posting 목록 조회, 생성

JBS 12 2023. 9. 14. 08:54

const { DataSource } = require('typeorm')
const dotenv = require('dotenv')
const jwt = require('jsonwebtoken')

dotenv.config()            //

const myDataSource = new DataSource({
    type : process.env.DB_TYPE,
    host : process.env.DB_HOST,
    port : process.env.DB_PORT,
    username : process.env.DB_USER,
    password : process.env.DB_PASSWORD,
    database : process.env.DB_NAME
})

myDataSource.initialize()
    .then(() => {
        console.log("Data Source has been initialized!_threadService")   // 알기 쉽게 
    })

 

 

// 포스팅 목록 가져오기 = read 
const readThreads = async (req, res) => {
    try {
        //스레드 받아오기 dbmate 테이블 보면서
        const getThread = await myDataSource.query(`
        SELECT
        users.nickname,        // 우리 thread create table에는  users.id 만 있는데 (thread read이니까 create table이 아닌가?) 
        threads.id AS postId,     // AS postId 가 뭐지 
        threads.content,
        threads.created_at AS createdAt,
        FROM threads
        INNER JOIN users ON threads.user_id = users.id   // 'threads 테이블의 user_id'와 'users 테이블의 id'와 같은 것을? 
        ORDER BY threads.created_at DESC;
        `)

        console.log("success");

        return res.status(200).json({
            getThread
        })
    } catch (error) {
        console.log(error)
    }
}


// 쓰레드 남기기, 게시물 남기기, create (로그인 한 사람만) 

const createThreads = async(req, res) => {
    try {

        //토큰 받음
        const token = req.headers.authorization;

        //토큰 없을 때
        if( ! token) {
            const error = new Error("TOKEN_ERROR")
            error.statusCode = 400
            error.code = "TOKEN_ERROR"
            throw error
        }

        //토큰 검증
        const {id} = jwt.verify(token, process.env.TYPEORM_JWT);

 


        //스레드 내용
        const { content } = req.body;
        //스레드 내용이 없을 때; content 한 글자 이상
        if(content.length === 0) {
            const error = new Error("CONTENT_TOO_SHORT")
            error.statusCode = 400
            error.code = "CONTENT_TOO_SHORT"
            throw error
        }

        //스레드 내용 저장
        const newPost = await myDataSource.query(`
        INSERT INTO threads (
            user_id,
            content
        ) VALUES (
            '${id}',
            '${content}'
        );
        `)           //title은 필요없는게, threads 상품 자체가 목록 조회가  contents로 나열되기 때문에. 

        console.log("new Post ID : ", newPost.id)
        console.log("new Post Content : ", newPost.content)

        //스레드 내용 출력
        return res.status(200).json({
            "code" : "writingSuccess"
        })
    } catch (error) {
        console.log(error)
        return res.status(400).json({
            "error" : error
        });
    }
}

module.exports = {
    readThreads,
    createThreads
}