Skip to main content

Command Palette

Search for a command to run...

[TIL] Blog Login, SignUp & additional features

04/19/23

Updated
View as Markdown
[TIL] Blog Login, SignUp & additional features

TIL

Issues encountered

  1. nested try-catch refactoring

  2. nested router 처리하기: https://stackoverflow.com/questions/25260818/rest-with-express-js-nested-router

What I tried

  1. 처음에는 mongoDB의 데이터들을 지우고 업데이트할 수 있는 deleteOne()과 updateOne() functions를 try-catch문 안에 넣어서 해당 함수 처리가 실패하였을 때 catch{}로 넘어가는 식으로 만들어서 nested try-catch문을 사용하게 되었었다. => 그러나, 위 두 함수는 Promise 형태이기 때문에 뒤에 .catch()를 통해 에러를 바로 잡을 수 있다.
try {
    const existingPost = await Posts.findOne({ userId, _id: _postId }).exec();
if (!existingPost)
    return res.status(403).json({ errorMessage: "게시글 수정의 권한이 존재하지 않습니다.",});
    try {
        await Posts.updateOne({ userId, _id: _postId }, { $set: { title, content } });

        res.status(200).json({ message: "게시글을 수정하였습니다." });
    } catch (error) {
        console.error(error);
        return res.status(401).json({
        errorMessage: "게시글이 정상적으로 수정되지 않았습니다.",});
    }
} catch (error) {
    console.error(error);
    res.status(400).json({ errorMessage: "게시글 수정에 실패하였습니다." });
}
  1. const router = express.Router({ mergeParams: true }); 이를 각 하위 라우터 파일들에 넣어주면 index.js에서 경로 처리를 할 수 있다.

     const express = require("express"); const router = express.Router(); const postsRouter = require("./posts.js"); const usersRouter = require("./users.js"); const commentsRouter = require("./comments.js");
    
     router.use("/users", [usersRouter]); router.use("/posts", [postsRouter]); router.use("/posts/:_postId/comments", [commentsRouter]);
    
     module.exports = router;
    

How I resolved the issues

try {
    const existingPost = await Posts.findOne({userId, _id: _postId,}).exec();
    if (!existingPost)
        return res.status(403).json({
             errorMessage: "게시글 수정의 권한이 존재하지 않습니다.",});
        await Posts.updateOne(
            { userId, _id: _postId },
            { $set: { title, content } }
        ).catch((error) => { // 여기서 catch()로 처리
            console.error(error);
            res.status(401).json({
                errorMessage: "게시글이 정상적으로 수정되지 않았습니다.",
            });
        });
        res.status(200).json({ message: "게시글을 수정하였습니다." });
} catch (error) {
        console.error(error);
        res.status(400).json({ errorMessage: "게시글 수정에 실패하였습니다."           });
}

What I newly learned

  1. bcrypt: to make password more secure by converting the user input password into the hashed password

  2. how to deal with the nested router

  3. Swagger!

  4. 스터디 하면서 배운거

    1. React의 useState나 component 안에서 state 변경 값이 유지되는 것이 내부적으로 클로저를 사용해서 가능하다! 클로저를 통해 스코프 내에서 변수의 값이 유지된다.

    2. 얕은 복사 깊은 복사

      • object 자체는 private이지만 object의 값들은 public이다
  • object의 값들 하나하나가 실제 값이 저장되어 있는 address를 가리키기 때문에 원본 object의 복사본이 값을 변경하는 것이 가능하다

  • depth가 2 이상이면 또 변경 불가

  • 깊은 복사는 recursion으로 구현해야함

    1. lodash: a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions,

What to learn next

  1. Change MongoDB to MySQL

  2. Learn Sequelize

Today I Learned

Part 1 of 50

Today I Learned!