-
Notifications
You must be signed in to change notification settings - Fork 0
/
levelHandler.js
72 lines (64 loc) · 1.81 KB
/
levelHandler.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
const Level = require("./levelModel");
const _ = require('lodash');
const bcrypt = require('bcrypt')
createLevel = async (name, author, text, answer) => {
try {
const salt = await bcrypt.genSalt(10);
const hashed = await bcrypt.hash(answer, salt);
const level = new Level ({
name: name,
author: author,
levelText: text,
answer: hashed
});
const result = await level.save();
return result;
}
catch(err) {
console.log("Error while making level for DB", err)
}
},
addEndpoint = async (objID) => {
try{
let lvl = await Level.findOneAndUpdate(
{_id : objID}, // filter
{ endpoint: String(objID).slice(-4)}, // update
{new: true}
) // returns updated object
return lvl.endpoint
}
catch (err) {
console.log("Error while adding Endpoint")
}
},
getAllLevels = async () => {
try {
let levels = await Level
.find()
//.limit()
.sort({ date: 1})
.select({ name: 1, author: 1, levelText:1 });
levels.forEach( (level, index, levelsArr) => {
return levelsArr[index] = _.pick(level, ['_id','name', 'author', 'levelText'])
})
return levels;
}
catch (err) {
console.error(err);
}
}
isAnsCorrect = async(endpoint, answer) => {
try {
const level = await Level.findOne({endpoint: endpoint})
const isValid = await bcrypt.compare(answer, level.answer);
return isValid
}
catch(err) {
console.error(err)
return err
}
}
module.exports.createLevel=createLevel;
module.exports.addEndpoint=addEndpoint;
module.exports.getAllLevels=getAllLevels;
module.exports.isAnsCorrect = isAnsCorrect;