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

58 lines
1.3 KiB
JavaScript

const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const posts = {};
const handleEvent = (type, data) => {
console.log(`Handling Event ${type}`, data);
if (type === 'PostCreated') {
const { id, title } = data;
posts[id] = { id, title, comments: [] };
}
if(type === 'CommentCreated') {
const { id, content, postId, status } = data;
const post = posts[postId];
post.comments.push({ id, content, status });
}
if(type === 'CommentUpdated') {
const { id, content, postId, status } = data;
const post = posts[postId];
const comment = post.comments.find(comment => comment.id === id);
comment.status = status;
comment.content = content;
}
}
app.get('/posts', (req, res) => {
res.send(posts);
});
app.post('/events', (req, res) => {
const { type, data } = req.body;
handleEvent(type, data);
res.send({});
});
app.listen(4002, async () => {
console.log('Listening on 4002');
try {
const res = await axios.get('http://localhost:4005/events');
for (let event of res.data) {
handleEvent(event.type, event.data);
}
}catch(error){
console.error(error);
}
});