# [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](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문을 사용하게 되었었다. =&gt; 그러나, 위 두 함수는 Promise 형태이기 때문에 뒤에 `.catch()`를 통해 에러를 바로 잡을 수 있다.
    

```javascript
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에서 경로 처리를 할 수 있다.
    
    ```javascript
    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

```javascript
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!](https://velog.io/@yzkim9501/swagger-autogen%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%82%B4-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EC%97%90-swagger-%EC%9E%90%EB%8F%99-%EC%A0%81%EC%9A%A9)
    
4. 스터디 하면서 배운거
    
    1. React의 useState나 component 안에서 state 변경 값이 유지되는 것이 내부적으로 클로저를 사용해서 가능하다! 클로저를 통해 스코프 내에서 변수의 값이 유지된다.
        
    2. 얕은 복사 깊은 복사
        
        * object 자체는 private이지만 object의 값들은 public이다
            
        
        * object의 값들 하나하나가 실제 값이 저장되어 있는 address를 가리키기 때문에 원본 object의 복사본이 값을 변경하는 것이 가능하다
            
        * depth가 2 이상이면 또 변경 불가
            
        * 깊은 복사는 recursion으로 구현해야함
            
    3. [lodash](https://velog.io/@kysung95/%EC%A7%A4%EB%A7%89%EA%B8%80-lodash-%EC%95%8C%EA%B3%A0-%EC%93%B0%EC%9E%90): 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
