-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (71 loc) · 2.05 KB
/
server.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
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const URI = process.env.MONGODB_URI || 'mongodb://localhost/database';
const PORT = process.env.OPENSHIFT_NODEJS_PORT || 8080;
const IP = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
const DB_NAME = process.env.DB_NAME;
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/secret', (req, res)=>{
res.sendFile(path.join(__dirname, 'secret.html'));
});
app.post('/secret', (req, res)=>{
MongoClient.connect(URI, {useNewUrlParser: true}, (err, client)=>{
if(err){
console.log(err);
}
else{
const db = client.db(DB_NAME);
const collection = db.collection('names');
const entry = {
name: req.body.name.toLowerCase(),
card: req.body.number + '_of_' + req.body.suit
};
collection.insertOne(entry, (err, result)=>{
if(err){
console.log(err);
}
else{
res.send('Inserted into databse');
}
});
db.close();
}
});
});
app.get('/:param*', (req,res)=>{
const name = req.url.slice(1).toLowerCase();
MongoClient.connect(URI, {useNewUrlParser: true}, (err, client)=>{
if(err){
console.log(err);
}
else{
const db = client.db(DB_NAME);
const collection = db.collection('names');
if(name === 'deleteall'){
collection.remove({});
res.send('database reset!');
}
else{
collection.find({name: name}).toArray((err,result)=>{
if(err){
console.log(err);
}
else if(result.length){
const card = result[result.length-1].card + '.png';
res.sendFile(path.join(__dirname + '/cards/' + card));
}
else{
res.sendStatus(404);
}
db.close();
});
}
}
});
});
app.listen(PORT, IP, ()=> console.log('Server listening on port' + PORT));