나의 발자취
[Node.js] 시퀄라이즈를 활용한 게시판 생성, curl 날려서 데이터 주고받기 - GET, PUT, DELETE 본문
지난 포스팅
2024.10.15 - [분류 전체보기] - [Node.js] 시퀄라이즈를 활용한 게시판 생성, curl 날려서 데이터 주고받기 - POST
[Node.js] 시퀄라이즈를 활용한 게시판 생성, curl 날려서 데이터 주고받기 - POST
npm init -ynpm i express nodemon sqlite3 sequelize sequelize-cli npx sequelize init * npx: node package executor로, 패키지를 실행할 때의 명령어~ 위 명령어 실행 후 app.js 파일 생성, 노드몬 정보 맞추기 그
wildguess.tistory.com
GET Posts - 모든 게시글 가져오기
다음으로 모든 게시글을 가져오는 GET 요청은 아래와 같이 간단하게 구현할 수 있다.
모든 게시글을 가져올 때에는 .findAll()을 쓰면 손쉽게 가져올 수 있다.
app.get("/posts", async (req, res) => {
// select * from posts;
const posts = await models.Post.findAll();
res.json({ data: posts });
});
GET Posts by id - 게시글 상세 가져오기
id값으로 상세 게시글을 가져오기 때문에, 이 때는 findByPk()로 가져온다 (find by Primary Key)
app.get("/posts/:id", async (req, res) => {
const id = req.params.id;
const post = await models.Post.findByPk(id);
if (post) {
res.status(200).json({ data: post });
} else {
res.status(404).json({ result: "post not found" });
}
});
그러면 의도한 대로 아래의 로그가 나오는 것이 보인다.
PUT (update) post - 게시글 업데이트
app.put("/posts/:id", async (req, res) => {
const id = req.params.id;
const { title, content } = req.body;
const post = await models.Post.findByPk(id);
if (post) {
post.title = title;
post.content = content;
await post.save();
res.status(200).json({data: post});
} else {
res.status(404).json({ result: "post not found" });
}
});
history | grep
id값이 2번인 것을 해보겠다.
그러면 아래와 같이 수정사항이 잘 반영된 것이 확인된다.
DELETE POST - 특정 포스트 삭제
를 해주기 위해 destroy()를 사용한다.
참고로, delete를 하는 메서드들은 여러개가 있다.
- destroyAll() - 한줄씩 지울때
truncate() - 통으로 날릴때
app.delete("/posts/:id", async (req, res) => {
// delete from posts;
const result = await models.Post.destroy({
where: {
id: req.params.id,
},
});
console.log(`destroyed result: ${result}`);
if (result) {
res.status(204).send();
} else {
res.status(404).json({ result: "post not found" });
}
});
'Backend' 카테고리의 다른 글
[Node.js] sequelize-CLI로 테이블(모델) 생성, 테이블 구조 변경 migration, seed 데이터 추가 (1) | 2024.10.16 |
---|---|
[Node.js] 시퀄라이저 - 댓글 기능 구현하기 (1) | 2024.10.16 |
[Node.js] 시퀄라이즈를 활용한 게시판 생성, curl 날려서 데이터 주고받기 - POST (2) | 2024.10.15 |
[Node.js] ORM 시퀄라이즈(Sequelize)를 활용해서 테이블 만들고 데이터 주고받기 (0) | 2024.10.15 |
[Node.js] GraphQL Schema 설계, mutation 타입 (0) | 2024.10.15 |
Comments