-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestions.js
58 lines (51 loc) · 1.87 KB
/
questions.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const express = require('express');
const axios = require('axios');
const { createProxyMiddleware } = require('http-proxy-middleware');
const logger = require('./config/winston');
const { redisSet, redisGet } = require('./config/redis');
const router = express.Router();
const destination = process.env.QUESTIONS_HOST || 'http://localhost:3020';
const options = {
target: destination,
changeOrigin: true,
};
// /qa/questions
router.get('/questions', (req, res) => {
const { page = 1, count = 5, productId } = req.query;
const key = `productId:${productId}:page${page}:count${count}`;
return redisGet(key).then((results) => {
if (results) {
return res.send(JSON.parse(results));
}
return axios.get(`${destination}/qa/questions?product_id=${productId}&page=${page}&count=${count}`).then(({ data }) => {
res.send(data);
return redisSet(key, JSON.stringify(data));
})
.catch((err) => {
logger.error(err);
res.status(500).send(`There was an error getting questions for product ${productId}`);
});
});
});
// /qa/questions/:question_id
router.get('/questions/:question_id/answers', (req, res) => {
const questionId = req.params.question_id;
const key = `question:${questionId}`;
return redisGet(key).then((results) => {
if (results) {
return res.send(JSON.parse(results));
}
return axios.get(`${destination}/qa/questions/${questionId}/answers`).then(({ data }) => {
res.send(data);
return redisSet(key, JSON.stringify(data));
})
.catch((err) => {
logger.error(err);
res.status(500).send(`There was an error getting answers for question ${questionId}`);
});
});
});
router.post('/questions*', createProxyMiddleware(options));
router.put('/questions*', createProxyMiddleware(options));
router.put('/answers*', createProxyMiddleware(options));
module.exports = router;