-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastcards.js
More file actions
60 lines (52 loc) · 1.65 KB
/
fastcards.js
File metadata and controls
60 lines (52 loc) · 1.65 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
//requirements
const express = require('express');
const rateLimiter = require('express-rate-limit');
require('dotenv').config();
const scraper = require('./scraper.js');
//initialization
const PORT = process.env.PORT || 3000;
const rateLimit = rateLimiter({
windowMs: 60000,
max: 20,
message: {err: 'Too many requests! To recieve unlimited key, message Treephones#4601 on discord.'}
});
let app = express();
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(rateLimit);
//static files
app.get('/statics/:page/:file', (req, res) => {
res.sendFile(`${__dirname}/statics/${req.params.page}/${req.params.file}`);
});
//routes
app.get(['/', '/home'], (req, res) => {
//homepage to come
res.sendFile(`${__dirname}/statics/home/index.html`);
});
app.post('/api/flashcards', (req, res) => {
let r = req.body;
if(!r.query) {
res.statusCode = 400;
res.json({err: "'query' header is required in request."});
return;
}
try {
scraper.getFlashcardResponse(r.query.replace(" ", "+"), r.max ? r.max : 10).then((response) => {
if(response.number_of_flashcards > 0) {
res.statusCode = 200;
res.json(response);
}
else {
res.statusCode = 404;
res.json({err: `Flashcards for '${r.query}' could not be found.`});
}
});
}
catch(e) {
res.statusCode = 500;
res.json({err: "Something went wrong while processing that request."});
}
});
app.listen(PORT);
console.log(`FastCards has started and is listening on port ${PORT}.`);