Skip to content

Commit d878e5d

Browse files
committed
user services refactor + test
1 parent 65d12ac commit d878e5d

File tree

14 files changed

+219
-192
lines changed

14 files changed

+219
-192
lines changed

src/controllers/error.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ export const ErrorController = {
99
},
1010

1111
errorHandler: (err: Error, req: Request, res: Response, next: NextFunction) => {
12+
res.status(500);
1213
if (process.env.ENV === 'dev') return res.json([err.message, err.stack]);
13-
return res.status(500).json(err.message);
14+
return res.json(err.message);
1415
}
1516
};

src/controllers/profile.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,15 @@ export const ProfileController = {
1616

1717
updateProfile: async (req: Request, res: Response, next: NextFunction) => {
1818
try {
19-
return res.json(await UserServices.updateUser(req.body.token.username, req.body.data));
19+
return res.json(await UserServices.updateUser(req.body.username, req.body.data));
2020
} catch (err) {
2121
return next(err);
2222
}
2323
},
2424

2525
deleteProfile: async (req: Request, res: Response, next: NextFunction) => {
2626
try {
27-
await UserServices.deleteUser(req.body.token.username)
28-
return res.redirect('/');
27+
return res.json(await UserServices.deleteUser(req.body.username));
2928
} catch (err) {
3029
return next(err);
3130
}

src/models/DbClient.ts

Lines changed: 44 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {MongoClient} from "mongodb";
44
export class DbClient {
55

66
static async connect(): Promise<any> {
7+
78
return new Promise((resolve, reject) => {
89
MongoClient.connect(Config.database.path, (err: Error, client: any) => {
910
if (err) return reject(err);
@@ -24,100 +25,69 @@ export class DbClient {
2425
}
2526

2627
static async insertMany(collection: string, data: any[]): Promise<any[]> {
27-
return this.connect()
28-
.then((client: any) => {
29-
return client.db(Config.database.db)
30-
.collection(collection)
31-
.insertMany(data)
32-
.then(() => {
33-
client.close();
34-
return data;
35-
});
36-
});
28+
const client: any = await this.connect();
29+
await client.db(Config.database.db);
30+
client.close();
31+
return data;
3732
}
3833

3934
static async insertOne(collection: string, data: any): Promise<any> {
40-
return this.connect()
41-
.then((client: any) => {
42-
return client.db(Config.database.db)
43-
.collection(collection)
44-
.insertOne(data)
45-
.then(() => {
46-
client.close();
47-
return data;
48-
});
49-
});
35+
const client: any = await this.connect();
36+
await client.db(Config.database.db)
37+
.collection(collection)
38+
.insertOne(data);
39+
client.close();
40+
return data;
5041
}
5142

5243
static async insertOneIfNotExist(collection: string, filter: any, data: any): Promise<any> {
53-
return this.connect()
54-
.then((client: any) => {
55-
return client.db(Config.database.db)
56-
.collection(collection)
57-
.findOne(filter)
58-
.then((result: any) => {
59-
if (result) throw new Error('data already exist');
60-
return this.insertOne(collection, data)
61-
.then(() => {
62-
return data;
63-
});
64-
});
65-
});
44+
const client: any = await this.connect();
45+
const result: any = await client.db(Config.database.db)
46+
.collection(collection)
47+
.findOne(filter);
48+
if (result) throw new Error('data already exist');
49+
await this.insertOne(collection, data);
50+
return data;
6651
}
6752

6853
static async find(collection: string): Promise<any[]> {
69-
return this.connect()
70-
.then((client: any) => {
71-
return client.db(Config.database.db)
72-
.collection(collection)
73-
.find()
74-
.toArray();
75-
});
54+
const client: any = await this.connect();
55+
return await client.db(Config.database.db)
56+
.collection(collection)
57+
.find()
58+
.toArray();
7659
}
7760

7861
static async findOne(collection: string, filter: any): Promise<any> {
79-
return this.connect()
80-
.then((client: any) => {
81-
return client.db(Config.database.db)
82-
.collection(collection)
83-
.findOne(filter)
84-
.then((result: any) => {
85-
client.close();
86-
return result;
87-
});
88-
});
62+
const client: any = await this.connect();
63+
const result: any = await client.db(Config.database.db)
64+
.collection(collection)
65+
.findOne(filter);
66+
client.close();
67+
return result;
8968
}
9069

9170
static async findOneAndUpdate(collection: string, filter: any, update: any): Promise<any> {
92-
return this.connect()
93-
.then((client: any) => {
94-
return client.db(Config.database.db)
95-
.collection(collection)
96-
.findOneAndUpdate(filter, {$set: update})
97-
.then(() => {
98-
client.close();
99-
return update;
100-
});
101-
});
71+
const client: any = await this.connect();
72+
const result: any = await client.db(Config.database.db)
73+
.collection(collection)
74+
.findOneAndUpdate(filter, {$set: update});
75+
client.close();
76+
return result;
10277
}
10378

10479
static async findOneAndUpdateOrInsert(collection: string, filter: any, update: any): Promise<any> {
105-
return this.connect()
106-
.then(() => {
107-
return this.findOne(collection, filter)
108-
.then(async (result: any) => {
109-
if (result) return this.findOneAndUpdate(collection, filter, update);
110-
else return this.insertOne(collection, update);
111-
});
112-
});
80+
const result: any = await this.findOne(collection, filter);
81+
if (result) return this.findOneAndUpdate(collection, filter, update);
82+
else return this.insertOne(collection, update);
11383
}
11484

11585
static async findOneAndDelete(collection: string, filter: any): Promise<any> {
116-
return this.connect()
117-
.then((client: any) => {
118-
return client.db(Config.database.db)
119-
.collection(collection)
120-
.findOneAndDelete(filter);
121-
});
86+
const client: any = await this.connect();
87+
const result: any = await client.db(Config.database.db)
88+
.collection(collection)
89+
.findOneAndDelete(filter);
90+
client.close();
91+
return result;
12292
}
12393
}

src/services/auth.ts

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,45 +6,22 @@ import {UserServices} from "./user";
66

77
export const AuthServices = {
88

9-
signin: async (username: string, password: string, passwordConfirmation: string): Promise<Token> => {
9+
signin: async (username: string, password: string, passwordConfirmation: string): Promise<User> => {
1010
if (_.isNil(username) || _.isNil(password) || _.isNil(passwordConfirmation)) throw new Error('Missing data');
1111
if (!Password.confirmPassword(password, passwordConfirmation)) throw new Error('Password not matching');
1212
if (!Password.difficultyPassword(password)) throw new Error('Password must contains at least 6 characters');
13-
14-
const user = await UserServices.addUser({
15-
username: username,
16-
password: password
17-
})
18-
.catch((err: Error) => {
19-
throw err;
20-
});
21-
22-
const token = new Token({
23-
userId: user.id,
13+
return UserServices.addUser({
2414
username: username,
2515
password: password
2616
});
27-
return AuthServices.setToken(user, token);
2817
},
2918

3019
login: async (username: string, password: string): Promise<Token> => {
3120
if (_.isNil(username) || _.isNil(password)) throw new Error('Missing data');
32-
3321
const user: User = await UserServices.getUser(username);
3422
const userPassword: Password = await UserServices.getPassword(username);
3523
const valid = userPassword.comparePassword(password);
36-
console.log(valid)
3724
if (valid === false) throw new Error(Translation[Config.language].INVALID_CREDENTIALS);
38-
39-
const token = new Token({
40-
userId: user.id,
41-
username: username,
42-
password: password
43-
});
44-
return AuthServices.setToken(user, token);
45-
},
46-
47-
setToken: async (user: User, token: Token): Promise<Token> => {
48-
return DbClient.findOneAndUpdateOrInsert(Config.database.collections.tokens, {userId: user.id}, token);
25+
return UserServices.setToken(user.username);
4926
}
5027
};

src/services/user.ts

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,15 @@ export const UserServices = {
1818

1919
addUser: async (data: any): Promise<User> => {
2020
if (_.isNil(data) || _.isNil(data.username) || _.isNil(data.password)) throw new Error(Translation[Config.language].EMPTY_DATA);
21-
let user: User = new User(data);
22-
user = new User(await DbClient.insertOneIfNotExist(Config.database.collections.users, {username: user.username}, user.store()));
23-
const password: Password = new Password(data);
24-
password.userId = user.id;
25-
await DbClient.insertOneIfNotExist(Config.database.collections.passwords, {userId: user.id}, password);
26-
return user;
21+
try {
22+
let user: User = new User(data);
23+
user = new User(await DbClient.insertOneIfNotExist(Config.database.collections.users, {username: user.username}, user.store()));
24+
await UserServices.setPassword(data.username, data.password);
25+
await UserServices.setToken(data.username);
26+
return user;
27+
} catch (err) {
28+
throw err;
29+
}
2730
},
2831

2932
getUsers: async (): Promise<User[]> => {
@@ -37,19 +40,28 @@ export const UserServices = {
3740
return new User((await DbClient.findOne(Config.database.collections.users, {username: username})));
3841
},
3942

40-
updateUser: async (username: string, update: string): Promise<User> => {
41-
return new User(await (DbClient.findOneAndUpdate(Config.database.collections.users, {username: username}, update)))
43+
updateUser: async (username: string, update: any): Promise<User> => {
44+
const user: User = await UserServices.getUser(username);
45+
return new User(await (DbClient.findOneAndUpdate(Config.database.collections.users, {_id: user.id}, update)))
4246
},
4347

4448
deleteUser: async (username: string): Promise<void> => {
45-
await DbClient.findOneAndDelete(Config.database.collections.users, {username: username});
46-
await UserServices.deletePassword(username);
47-
await UserServices.deleteToken(username);
49+
try {
50+
await DbClient.findOneAndDelete(Config.database.collections.users, {username: username})
51+
await UserServices.deletePassword(username);
52+
await UserServices.deleteToken(username);
53+
} catch (err) {
54+
throw err;
55+
}
4856
},
4957

50-
getToken: async (username: string): Promise<Token> => {
58+
setPassword: async (username: string, password: string): Promise<Password> => {
5159
const user: User = await UserServices.getUser(username);
52-
return new Token(await DbClient.findOne(Config.database.collections.tokens, {userId: user.id}));
60+
const psswrd: Password = new Password({
61+
userId: user.id,
62+
password: password
63+
});
64+
return await DbClient.insertOneIfNotExist(Config.database.collections.passwords, {userId: user.id}, psswrd);
5365
},
5466

5567
getPassword: async (username: string): Promise<Password> => {
@@ -62,9 +74,20 @@ export const UserServices = {
6274
return DbClient.findOneAndDelete(Config.database.collections.passwords, {userId: user.id});
6375
},
6476

77+
setToken: async (username: string) => {
78+
const user: User = await UserServices.getUser(username);
79+
const token = new Token({userId: user.id});
80+
return DbClient.findOneAndUpdateOrInsert(Config.database.collections.tokens, {userId: user.id}, token);
81+
},
82+
6583
deleteToken: async (username: string): Promise<void> => {
6684
const user: User = await UserServices.getUser(username);
6785
return DbClient.findOneAndDelete(Config.database.collections.tokens, {userId: user.id});
86+
},
87+
88+
getToken: async (username: string): Promise<Token> => {
89+
const user: User = await UserServices.getUser(username);
90+
return new Token(await DbClient.findOne(Config.database.collections.tokens, {userId: user.id}));
6891
}
6992
}
7093
;

src/test/index.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
21
describe('config', () => {
32
require('./config');
43
});
54

65
describe('models', () => {
7-
require('./models');
6+
require('./models');
87
});
9-
/*
8+
109
describe('services', () => {
11-
require('./services');
10+
require('./services');
1211
});
13-
*/
12+

0 commit comments

Comments
 (0)