Skip to content

Commit

Permalink
duplicate email exists error handling for create/update user
Browse files Browse the repository at this point in the history
  • Loading branch information
asad-mlbd committed Jun 8, 2020
1 parent 15f1313 commit 4965f8b
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions services/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as userRepo from "./../repositories/user.repository.ts";
import { httpErrors, HttpError } from "https://deno.land/x/[email protected]/mod.ts";
import { httpErrors } from "https://deno.land/x/[email protected]/mod.ts";

/**
* get user by id
Expand All @@ -26,26 +26,43 @@ export const getUsers = async () => {
*/
export const createUser = async (userData: any) => {
// todo: validation
// todo: catch db error
const user = await userRepo.createUser(userData);
return user;
try {
const user = await userRepo.createUser(userData);
return user;
} catch (err) {
const { message } = err;
if (message.match("email_unique")) {
throw new httpErrors.BadRequest(
`Already user exists with email ${userData.email}`,
);
}
throw err;
}
};

/**
* update user
*/
export const updateUser = async (id: number, userData: any) => {
// todo: validation
// todo: catch db error
const result = await userRepo.updateUser(id, userData);
if (result["affectedRows"]) {
const user = await userRepo.getUserById(id);
if (user) {
return user;
try {
const result = await userRepo.updateUser(id, userData);
if (result["affectedRows"]) {
const user = await userRepo.getUserById(id);
if (user) {
return user;
}
}
throw new httpErrors.NotFound("User not found");
} catch (err) {
const { message } = err;
if (message.match("email_unique")) {
throw new httpErrors.BadRequest(
`Already user exists with email ${userData.email}`,
);
}
throw err;
}

throw new httpErrors.NotFound("User not found");
};

/**
Expand Down

0 comments on commit 4965f8b

Please sign in to comment.