-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats-for-host.js
85 lines (69 loc) · 1.85 KB
/
stats-for-host.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
"use strict"
const mongoose = require("mongoose");
const MONGO_URI = process.env.MONGO_URI;
const User = require("./models/user");
const arrName = ["animal", "emoji", "color", "first", "now"];
let connection = null;
const connectDB = () => {
if (connection && mongoose.connection.readyState === 1) return;
mongoose.connect(MONGO_URI, { }).then(
conn => {
connection = conn;
}
);
};
module.exports.handler = async (event, context) => {
const hostId = event.pathParameters.hostId;
const userId = event.requestContext.authorizer.lambda.userId;
if(hostId != userId)
return {
statusCode: "403",
body: JSON.stringify({
"message": "User Not Allowed",
})
};
connectDB();
try{
const hostUser = await User.findOne({ id: hostId }).populate("friends");
const total = hostUser.animal.reduce((sum, val) => sum + val, 0);
if (total === 0)
return {
statusCode: "204",
body: JSON.stringify({
"message" : "No Result Yet",
})
};
let result = {};
arrName.forEach((name, idx) => {
const arr = hostUser[name];
const first = Math.max(...arr);
const firstIdx = arr.indexOf(first);
const firstObj = {
index: firstIdx,
percent: Math.floor((first / total) * 100),
};
arr[firstIdx] = 0;
const second = Math.max(...arr);
const secondObj = {
index: arr.indexOf(second),
percent: Math.floor((second / total) * 100),
};
result[name] = [firstObj, secondObj];
});
return {
statusCode: "200",
body: JSON.stringify({
"message": "Stats Result",
"data" : result
})
};
} catch(err){
console.log(err);
return {
statusCode: "400",
body: JSON.stringify({
"message": "Bad Request",
})
};
}
};