-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
duplicate email exists error handling for create/update user
- Loading branch information
Showing
1 changed file
with
29 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
@@ -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"); | ||
}; | ||
|
||
/** | ||
|