const express = require('express');
const bodyParser = require('body-parser');
const { randomBytes } = require('crypto');
console.log(randomBytes(4).toString('hex'));
const app = express();
app.use(bodyParser.json());
const posts = {};
app.get('/posts', (req, res) => {
res.send(posts);
});
app.post('/posts', (req, res) => {
const id = randomBytes(4).toString('hex');
const { title } = req.body;
posts[id] = {
id,
title
};
res.status(201).send(posts[id]);
});
app.listen(4000, () => {
console.log('Listening on 4000');
});
posts[id] 로 배열이 아닌 객체에 담고 있을떄 후에 모양은
{
"81f137ec": {
"id": "81f137ec",
"title": "Fairast Post"
},
"0d855591": {
"id": "0d855591",
"title": "Fairast Post"
},
"3a9a673a": {
"id": "3a9a673a",
"title": "Fairast Post"
}
}
포스트를 생성하였으니 comments도 생성해보자
const express = require('express');
const bodyParser = require('body-parser');
const { randomBytes } = require('crypto');
const app = express();
app.use(bodyParser.json());
const commentsByPostId = {};
app.get('/posts/:id/comments', (req, res) => {
res.send(commentsByPostId[req.params.id] || []);
});
app.post('/posts/:id/comments', (req, res) => {
const commentId = randomBytes(4).toString('hex');
const { content } = req.body;
const comments = commentsByPostId[req.params.id] || [];
comments.push({ id: commentId, content });
commentsByPostId[req.params.id] = comments;
console.log(commentsByPostId)
res.status(201).send(comments);
});
app.listen(4001, () => {
console.log('Listening on 4001');
});
댓글 comments 생성 시 형태는
{
'123': [
{ id: '82607145', content: 'content01' },
{ id: '1da2c316', content: 'content01' },
{ id: '44fbccd5', content: 'content01' }
],
'222': [
{ id: '240528fa', content: 'content01' },
{ id: 'e72a1ac7', content: 'content01' },
{ id: '39b2ee6c', content: 'content01' }
]
}