-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
65 lines (53 loc) · 1.57 KB
/
database.js
File metadata and controls
65 lines (53 loc) · 1.57 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
const {MongoClient} = require('mongodb');
const bcrypt = require('bcrypt');
const uuid = require('uuid');
const userName = process.env.MONGOUSER;
const password = process.env.MONGOPASSWORD;
const hostname = process.env.MONGOHOSTNAME;
if (!userName) {
throw Error('Database not configured. Set environment variables');
}
const url = `mongodb+srv://${userName}:${password}@${hostname}`;
const client = new MongoClient(url);
const scoreCollection = client.db('startup').collection('scores');
const userCollection = client.db('startup').collection('user');
/*functions for scores*/
function addScore(score) {
scoreCollection.insertOne(score);
}
function getHighScores() {
const query = {score: {$gt: 0}};
const options = {
sort: {score: -1, minutes: 1, seconds: 1},
limit: 10,
};
const cursor = scoreCollection.find(query, options);
return cursor.toArray();
}
/*functions for user info*/
function getUser(userName) {
return userCollection.findOne({ userName: userName });
}
function getUserByToken(token){
return userCollection.findOne({ token: token });
}
async function createUser(userName, password) {
console.log("in database createUser");
// Hash the password before we insert it into the database
const passwordHash = await bcrypt.hash(password, 10);
console.log("createUser: past hash");
const user = {
userName: userName,
password: passwordHash,
token: uuid.v4(),
};
await userCollection.insertOne(user);
return user;
}
module.exports = {
getUser,
getUserByToken,
createUser,
addScore,
getHighScores,
};