forked from kubowania/minesweeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (93 loc) · 2.37 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
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
95
96
97
98
99
100
var express = require('express');
const url = require('url')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var morgan = require("morgan")
var cors = require('cors')
const getEnv = require('dotenv').config()
var app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("common"))
const port = process.env.PORT || 3000
var whitelist = ['https://www.quocthinhvo.dev', 'https://escape12c10.herokuapp.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
mongoose.connect(process.env.DBSTR);
var winnerSchema = mongoose.Schema({
name: String,
time: Number,
date: String
});
var Winner = mongoose.model("winner", winnerSchema);
app.get('/', function(req, res){
res.send({
"message": "REST API zone"
}).status(200)
});
app.post('/add', function (req, res) {
let datetime = new Date();
let winnerData = req.body;
if (!winnerData.name || !winnerData.time) {
res.send({
"message": "Wrong data"
}).status(403)
} else
{
let winner = new Winner({
name: winnerData.name,
time: winnerData.time,
date: datetime.toISOString().slice(0,10)
})
winner.save(function (err){
if (err) {
res.send({
"message": "error",
"content": err
}).status(500)
} else res.redirect(301, "https://quocthinhvo.dev/escape12c10");
})
}
})
app.get("/ranks", function (req, res) {
let top = req.query.top
Winner.find()
.limit(top)
.sort({
time: 1
})
.then((result)=>{
res.status(200).send(result)
})
.catch((err)=>{
res.status(500).send({message: "Some error with database"})
})
})
app.get("/user/:username", function (req, res) {
let username = req.params.username
let num = 10;
num = req.query.num;
Winner.find()
.find({
name: username
})
.limit(num)
.then((result)=>{
res.status(200).send(result)
})
.catch((err)=>{
res.status(500).send({message: "Some error with database"})
})
})
app.listen(port);