-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
53 lines (42 loc) · 1.4 KB
/
index.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
const express = require('express');
const request = require('request');
const LimitingMiddleware = require('limiting-middleware');
const app = express();
app.use(new LimitingMiddleware().limitByIp());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/', (req, res) => {
res.send('Try /deck/new/shuffle, or /deck/:deck_id/draw');
});
// make a request to the deck of cards api that the student can use to get around cors
app.get('/deck/new/shuffle', (req, res, next) => {
/**
* 7/3/19. The /shuffle endpoint is currently having issues in the base API.
*/
request({
url: 'https://deckofcardsapi.com/api/deck/new/shuffle/'
}, (error, response, body) => {
if (body.substring(0, 1) === '{') {
return res.json(JSON.parse(body));
}
return next(new Error('https://deckofcardsapi.com/api/deck/new/ returns unexpected data'));
});
});
app.get('/deck/:deck_id/draw', (req, res) => {
const { deck_id } = req.params;
request({
url: `https://deckofcardsapi.com/api/deck/${deck_id}/draw/`
}, (error, response, body) => {
res.json(JSON.parse(body));
});
});
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
type: 'error', message: err.message
})
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening for requests on ${PORT}`));