-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (78 loc) · 2.56 KB
/
server.js
File metadata and controls
91 lines (78 loc) · 2.56 KB
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
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const { getRates, getSymbols, getHistoricalRate } = require('./lib/fixer-service');
const { convertCurrency } = require('./lib/free-currency-service');
const app = express();
const port = process.env.PORT || 3000;
// Set public folder as root
app.use(express.static('public'));
// Parse POST data as URL encoded data
app.use(bodyParser.urlencoded({
extended: true,
}));
// Parse POST data as JSON
app.use(bodyParser.json());
// Provide access to node_modules folder
app.use('/scripts', express.static(`${__dirname}/node_modules/`));
const errorHandler = (err, req, res) => {
if (err.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
res.status(403).send({ title: 'Server responded with an error', message: err.message });
} else if (err.request) {
// The request was made but no response was received
res.status(503).send({ title: 'Unable to communicate with server', message: err.message });
} else {
// Something happened in setting up the request that triggered an Error
res.status(500).send({ title: 'An unexpected error occurred', message: err.message });
}
};
// Fetch Latest Currency Rates
app.get('/api/rates', async (req, res) => {
try {
const data = await getRates();
res.setHeader('Content-Type', 'application/json');
res.send(data);
} catch (error) {
errorHandler(error, req, res);
}
});
// Fetch Symbols
app.get('/api/symbols', async (req, res) => {
try {
const data = await getSymbols();
res.setHeader('Content-Type', 'application/json');
res.send(data);
} catch (error) {
errorHandler(error, req, res);
}
});
// Convert Currency
app.post('/api/convert', async (req, res) => {
try {
const { from, to } = req.body;
const data = await convertCurrency(from, to);
res.setHeader('Content-Type', 'application/json');
res.send(data);
} catch (error) {
errorHandler(error, req, res);
}
});
// Fetch Currency Rates by date
app.post('/api/historical', async (req, res) => {
try {
const { date } = req.body;
const data = await getHistoricalRate(date);
res.setHeader('Content-Type', 'application/json');
res.send(data);
} catch (error) {
errorHandler(error, req, res);
}
});
// Redirect all traffic to index.html
app.use((req, res) => res.sendFile(`${__dirname}/public/index.html`));
app.listen(port, () => {
// eslint-disable-next-line no-console
console.log('listening on %d', port);
});