Skip to content

Commit

Permalink
Simplified duplicate user creation check
Browse files Browse the repository at this point in the history
  • Loading branch information
robbdimitrov committed Oct 12, 2019
1 parent 8e1c5a4 commit a18b23f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 30 deletions.
37 changes: 8 additions & 29 deletions backend/src/services/db-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,27 +285,6 @@ class DBClient {
});
}

async userNotExists(username, email) {
const client = await this.get();

return new Promise((resolve, reject) => {
client.db().collection('users').aggregate([
{ $match: { $or: [{ email }, { username }] } },
{ $project: { _id: 1, username: 1, email: 1 } },
]).toArray((err, result) => {
if (result.length > 0) {
const firstUser = result[0];
if (firstUser.email === email) {
return reject(new Error('User with this email already exists'));
} else if (firstUser.username === username) {
return reject(new Error('User with this username already exists'));
}
}
resolve();
});
});
}

/**
* Creates a user in the database for a given User object
*
Expand All @@ -316,15 +295,15 @@ class DBClient {
const client = await this.get();

return new Promise((resolve, reject) => {
this.userNotExists(user.username, user.email).then(() => {
client.db().collection('users').insertOne(user, (error, result) => {
if (error) {
return reject(error);
client.db().collection('users').insertOne(user, (error, result) => {
if (error) {
if (error.message.includes('email')) {
return reject(new Error('User with this email already exists'));
} else {
return reject(new Error('User with this username already exists'));
}
resolve(result);
});
}).catch((error) => {
return reject(error);
}
resolve(result);
});
});
}
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
volumes:
- image_data:/data/images
environment:
- DATABASE_URI=mongodb://db:27017/pixelgram
- DATABASE_URI=mongodb://database:27017/pixelgram
- PORT=3000
- SECRET=7f40a8c2c68f47ef7b896586b012ae34

Expand Down

0 comments on commit a18b23f

Please sign in to comment.