-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserService.js
More file actions
136 lines (115 loc) · 3.48 KB
/
Copy pathUserService.js
File metadata and controls
136 lines (115 loc) · 3.48 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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//"use strict";
var fs = require('fs');
var util = require('./util');
class UserService{
constructor()
{
var ldata = fs.readFileSync('UserCollections.json', 'utf8');
if(ldata){
this.data = JSON.parse(ldata);
}
else{
this.data = [];
}
}
getAllUsers()
{
var users = [];
for(var i in this.data){
let cloneData = Object.assign({}, this.data[i]);
delete cloneData.password;
users.push( cloneData );
}
return users;
};
getUser(userId)
{
for (var i in this.data)
{
if(this.data[i].id == userId)
{
let cloneData = Object.assign({}, this.data[i]);
delete cloneData.password;
return cloneData;
}
}
return null;
}
addUser(user)
{
for (var i in this.data)
{
if(this.data[i].email == user.email)
{
throw "Duplicate";
}
}
var newUser = {};
newUser.id = util.unique();
newUser.name = user.name;
newUser.email = user.email;
newUser.password = user.password;
newUser.creationTime = Date.now();
newUser.lmTime = newUser.creationTime;
this.data.push(newUser);
// Write data in file
var json = JSON.stringify( this.data );
fs.writeFile('UserCollections.json', json, 'utf8', function(){
console.log("New user saved in file");
});
return newUser;
}
updateUser(userId, user)
{
for (var i in this.data)
{
if(this.data[i].id == userId)
{
var oldObj = this.data[i];
oldObj.lmTime = Date.now();
oldObj.name = user.name;
oldObj.email = user.email;
oldObj.password = user.password;
// Write data in file
let json = JSON.stringify(this.data);
fs.writeFile('UserCollections.json', json, 'utf8',function(){
console.log("User is updated in file");
});
return oldObj;
}
}
return null;
}
deleteUser(userId)
{
for (var i in this.data)
{
if(this.data[i].id == userId)
{
this.data.splice(i,1);
// Remove data from file
let json = JSON.stringify(this.data);
fs.writeFileSync('UserCollections.json', json, 'utf8', function(){
console.log("User is deleted from file");
});
return this.data[i];
}
}
return null;
}
login(loginData)
{
for (var i in this.data)
{
if(this.data[i].email == loginData.email)
{
if(this.data[i].password == loginData.password)
{
return this.data[i];
}
}
}
return null;
}
};
module.exports = UserService;