-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.js
98 lines (89 loc) · 2.36 KB
/
utility.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
import jwt from 'jsonwebtoken';
import dotenv from "dotenv";
import User from './models/userSchema.js';
//utility config
dotenv.config({ silent: process.env.NODE_ENV === 'production' });
const SECRET_KEY = process.env.SECRET_KEY || 'q!w@e3R$t%y^u7*i(u)i*o_p+(efo*(3rqn s*y9q34n 309r389@939)(#$@#*U)#dasaha faq';
//token decoding function
const decodeJWT = (token, ip) => {
let decoded;
try {
decoded = jwt.verify(token, SECRET_KEY);
} catch (err) {
decoded = {id: undefined };
}
return decoded;
}
const addToUserList = (fieldName, id, val) => {
let update = { $push: {} };
update.$push[fieldName] = {
$each: [val]
};
let filter = {
_id: id
};
return new Promise((resolve, reject) => {
User.findOneAndUpdate(filter, update, (err, doc) => {
if (err || doc === null) {
console.log(err);
console.log("error: ");
reject(Error(false));
}
else {
resolve(true);
}
});
});
}
const removeFromUserList = (fieldName, id, val) => {
let update = { $pull: {} };
update.$pull[fieldName] = {
$in: [val]
};
let filter = {
_id: id
};
return new Promise((resolve, reject) => {
User.findOneAndUpdate(filter, update, (err, doc) => {
if (err || doc === null) {
console.log(err);
console.log("error: ");
reject(Error(false));
}
else {
resolve(true);
}
});
});
}
const moveBetweenUserList = (fieldName, id, val, fromFieldName) => {
let update = {
$pull: {
[fromFieldName]: {
$in: [val]
}
},
$push: {
[fieldName]: {
$each: [val]
}
}
};
let filter = {
_id: id
};
console.log(update);
return new Promise((resolve, reject) => {
User.findOneAndUpdate(filter, update, (err, doc) => {
if (err || doc === null) {
console.log(err);
console.log("error: ");
reject(Error(false));
}
else {
resolve(true);
}
});
});
}
export {decodeJWT,addToUserList,moveBetweenUserList,removeFromUserList};