Files
microservices-course/blog/comments/index.js
2021-08-01 17:19:21 -04:00

59 lines
1.5 KiB
JavaScript

const { randomBytes } = require('crypto');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const commentsByPostID = {};
app.get('/posts/:id/comments', (req, res) => {
res.send(commentsByPostID[req.params.id] || []);
});
app.post('/posts/:id/comments', async (req, res) => {
const commentID = randomBytes(4).toString('hex');
const { content } = req.body;
const comments = commentsByPostID[req.params.id] || [];
comments.push({ id: commentID, content, status: 'pending' })
commentsByPostID[req.params.id] = comments;
await axios.post('http://localhost:4005/events', {
type: 'CommentCreated',
data: {
id: commentID, content, postId: req.params.id, status: 'pending'
}
}).catch(error => console.log(error));
res.status(201).send(comments);
});
app.post('/events', async (req, res) => {
console.log('Received Event', req.body.type);
const { type, data } = req.body;
if(type === 'CommentModerated') {
const { postId, id, status, content } = data;
const comments = commentsByPostID[postId];
const comment = comments.find(comment => comment.id === id);
comment.status = status;
await axios.post('http://localhost:4005/events', {
type: 'CommentUpdated',
data: { id, status, postId, content }
}).catch(error => console.log(error));
}
res.send({});
});
app.listen(4001, () => {
console.log('Listening on 4001');
});