반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 홈트
- 달리기
- 월별 운동일지
- axios
- 활동 킬로칼로리
- express
- 박스점프
- 걷기
- 러닝
- 크로스핏
- 운동일지
- 메디패치
- dml
- nodejs
- SQL
- 습윤밴드
- node.js
- git
- node
- MySQL
- 위코드
- github
- 드림코딩
- 독서 리뷰
- code kata
- wecode
- JavaScript
- Til
- Udemy
- dql
Archives
- Today
- Total
RISK IT
[TIL14_23.1.22.] [Node] Express - 'westagram' 게시글 수정, 게시글 지우기, 좋아요 누르기 본문
IT/TIL
[TIL14_23.1.22.] [Node] Express - 'westagram' 게시글 수정, 게시글 지우기, 좋아요 누르기
nomoremystery 2023. 1. 23. 16:25반응형
작업 내용
- 게시글 수정하기
- 게시글 지우기
- 좋아요 누르기
전체 소스코드
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { DataSource } = require('typeorm');
const mysqlDataSource = new DataSource({
type: process.env.TYPEORM_CONNECTION,
host: process.env.TYPEORM_HOST,
port: process.env.TYPEORM_PORT,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
});
mysqlDataSource
.initialize()
.then(() => {
console.log('Data Source has been initialized!');
})
.catch((err) => {
console.error('Error during Data Source initialization', err);
mysqlDataSource.destroy();
});
const app = express();
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// health check
app.get('/ping', (req, res) => {
res.status(200).json({ message: 'pong' });
});
app.post('/users/signup', async (req, res) => {
const { name, email, password, profileImage } = req.body;
await mysqlDataSource.query(
`INSERT INTO users (
name,
email,
password,
profile_image
)
VALUES (
?,
?,
?,
?
);
`,
[name, email, password, profileImage]
);
res.status(201).json({ message: 'userCreated' });
});
app.post('/posts/users', async (req, res) => {
const { title, content, postImgUrl, userId } = req.body;
await mysqlDataSource.query(
`INSERT INTO posts (
title,
content,
post_image_url,
user_id
)
VALUES (
?,
?,
?,
?
);
`,
[title, content, postImgUrl, userId]
);
res.status(201).json({ message: 'postCreated' });
});
app.get('/lookup', async (req, res) => {
await mysqlDataSource.query(
`SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
p.id AS postingId,
p.post_image_url AS postingImageUrl,
p.content AS postingContent
FROM posts p
INNER JOIN users u ON u.id = p.user_id;
`,
(err, data) => {
res.status(200).json({ data });
}
);
});
app.get('/users/lookup', async (req, res) => {
await mysqlDataSource.query(
`SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
JSON_ARRAYAGG(postings_json.posting_id) AS postings
FROM users u
INNER JOIN (
SELECT
p.id,
JSON_OBJECT(
"postingId", id,
"postingImageUrl", post_image_url,
"postingContent", content
) AS posting_id
FROM posts p
) postings_json
WHERE u.id=1;
`,
(err, data) => {
res.status(200).json({ data });
}
);
});
app.patch('/posts/update/:userId/:postId', async (req, res) => {
const { userId, postId } = req.params;
const { content } = req.body;
await mysqlDataSource.query(
`UPDATE
posts
SET
content = ?
WHERE
user_id = ${userId} AND id = ${postId}
`,
[content]
);
await mysqlDataSource.query(
`SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
p.id AS postingId,
p.post_image_url AS postingImageUrl,
p.content AS postingContent
FROM posts p
INNER JOIN users u ON u.id = p.user_id
WHERE u.id=${userId} AND p.id=${postId}
`,
(err, data) => {
res.status(201).json({ data });
}
);
});
app.delete('/posts/delete/:postId', async (req, res) => {
const { postId } = req.params;
await mysqlDataSource.query(
`DELETE
FROM posts
WHERE posts.id = ${postId}
`
);
res.status(200).json({ message: 'postingDeleted' });
});
app.post('/likes/:userId/:postId', async (req, res) => {
const { userId, postId } = req.params;
await mysqlDataSource.query(
`INSERT INTO likes (
user_id,
post_id
)
VALUES (
?,
?
);
`,
[userId, postId]
);
res.status(201).json({ message: 'likeCreated' });
});
const PORT = process.env.PORT;
const start = async () => {
try {
app.listen(PORT, () => console.log(`Server is listening on ${PORT}!!`));
} catch (err) {
console.error(err);
}
};
start();
추가된 부분
// 게시글 수정하기
app.patch('/posts/update/:userId/:postId', async (req, res) => {
const { userId, postId } = req.params;
const { content } = req.body;
await mysqlDataSource.query(
`UPDATE
posts
SET
content = ?
WHERE
user_id = ${userId} AND id = ${postId}
`,
[content]
);
await mysqlDataSource.query(
`SELECT
u.id AS userId,
u.profile_image AS userProfileImage,
p.id AS postingId,
p.post_image_url AS postingImageUrl,
p.content AS postingContent
FROM posts p
INNER JOIN users u ON u.id = p.user_id
WHERE u.id=${userId} AND p.id=${postId}
`,
(err, data) => {
res.status(201).json({ data });
}
);
});
// 게시글 지우기
app.delete('/posts/delete/:postId', async (req, res) => {
const { postId } = req.params;
await mysqlDataSource.query(
`DELETE
FROM posts
WHERE posts.id = ${postId}
`
);
res.status(200).json({ message: 'postingDeleted' });
});
// 좋아요 누르기
app.post('/likes/:userId/:postId', async (req, res) => {
const { userId, postId } = req.params;
await mysqlDataSource.query(
`INSERT INTO likes (
user_id,
post_id
)
VALUES (
?,
?
);
`,
[userId, postId]
);
res.status(201).json({ message: 'likeCreated' });
});
req.params
를 이용해서 url 주소의 경로를 매개변수로 저장.
이를 활용해서 특정 id에 대한 내용만 쉽게 삭제 할 수 있었다.
반응형
'IT > TIL' 카테고리의 다른 글
[TIL16_23.1.24.] git 공부 & code kata 복습 (0) | 2023.01.24 |
---|---|
[TIL15_23.1.23.] [Node] Express - 'westagram' 특정 유저 게시글 조회 SQL문 수정 (0) | 2023.01.24 |
[TIL13_23.1.21.] [Node] Express - 'westagram' 게시글 등록, 전체 게시글 조회, 특정 게시글 조회 코드 작성 (0) | 2023.01.21 |
[TIL12_23.1.20.] [Node] Express 유저회원가입 코드 작성 (0) | 2023.01.21 |
[TIL11_23.1.19.] [Node] Express 초기 환경세팅 중 javascript 및 typeorm 구문 분석 (0) | 2023.01.19 |