-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
94 lines (80 loc) · 2.65 KB
/
app.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const express = require("express");
const axios = require("axios");
const redis = require("redis");
const cors = require('cors');
const dotenv = require("dotenv");
dotenv.config();
const multer = require('multer');
const inMemoryStorage = multer.memoryStorage();
const uploadStrategy = multer({storage: inMemoryStorage}).single('image');
const app = express();
app.use(cors());
// setup redis client
const client = redis.createClient({
port: process.env.REDIS_PORT,
host: process.env.REDIS_HOST,
password: process.env.REDIS_PASSWORD,
});
// redis store configs
const usersRedisKey = "store:student";
// start express server
const PORT = process.env.PORT || 5001;
// users endpoint with caching
app.get("/student/get", (req, res) => {
// try to fetch the result from redis
return client.get(usersRedisKey, (err, students) => {
if (students) {
return res.json({source: "cache", data: JSON.parse(students)});
// if cache not available call API
} else {
// get data from remote API
axios
.get("https://uokse-app.azurewebsites.net/student/get")
.then((students) => {
// save the API response in redis store
client.setex(usersRedisKey, 3600, JSON.stringify(students.data));
// send JSON response to client
return res.json({source: "api", data: students.data});
})
.catch((error) => {
// send error to the client
return res.json(error.toString());
});
}
});
});
// user details endpoint
app.get("/", (req, res) =>
res.send("Service 2 works...")
);
app.post("/file/upload", uploadStrategy, (req, res) => {
try {
axios
.post("https://uokse15-16.azurewebsites.net/api/HttpTrigger", {
filedata: req.file.buffer,
filename: req.file.originalname
})
.then((Res) => {
if (Res.status === 200) {
return res.status(200).json({
message: 'Image Uploaded!',
statusCode: 200
});
} else {
throw error;
}
})
.catch(e => {
return res.status(200).json({
message: 'Image Upload failed!',
statusCode: 400
});
console.error(e);
});
} catch (e) {
console.error(e);
}
});
app.listen(PORT, () => {
console.log("Server listening on port:", PORT);
});