Skip to content

Commit

Permalink
Merge pull request #1162 from tomrule007/refactor/trycatch-unknown
Browse files Browse the repository at this point in the history
Refactor/try catch unknown
  • Loading branch information
tomrule007 committed Oct 26, 2021
2 parents 909a976 + eda2552 commit 4b140cb
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 221 deletions.
10 changes: 5 additions & 5 deletions helpers/admin/adminHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { reach } from 'yup'
import { reach, ValidationError } from 'yup'
import _ from 'lodash'
import { DROP_DOWN, TEXT_AREA, MD_INPUT } from '../../components/FormCard'

// creates usuable array from graphql data to use as a prop when using FormCard component
// creates useable array from graphql data to use as a prop when using FormCard component
export const getPropertyArr = (
options: any,
deleteProps?: string[],
Expand Down Expand Up @@ -84,7 +84,7 @@ export const errorCheckSingleField = async (
await reach(schema, title, null, null).validate(data[title])
} catch (err) {
valid = false
properties[propertyIndex].error = err.message
properties[propertyIndex].error = (err as Error).message
}

// remove error message(if present) if field is valid
Expand All @@ -107,9 +107,9 @@ export const errorCheckAllFields = async (properties: any, schema: any) => {
} catch (err) {
// errors is an array of error messages
// inner is an array of objects containing more error information
const { errors, inner } = err
const { errors, inner } = err as ValidationError

inner.forEach((innerObj: any, errorIndex: number) => {
inner.forEach((innerObj, errorIndex) => {
// get index of property with title equal to value of innerObj.path
const titleIndex = properties.findIndex(
(property: any) => property.title === innerObj.path
Expand Down
6 changes: 2 additions & 4 deletions helpers/controllers/alertController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ describe('Alert controller tests', () => {
expect(removeAlert({}, { id: 5 }, ctx)).resolves.toEqual({ success: true })
})
test('Should throw error if no id provided when removing alert', async () => {
prismaMock.alert.delete.mockRejectedValueOnce('No alert id provided')
expect(removeAlert({}, {}, ctx)).rejects.toThrowError(
'No alert id provided'
)
prismaMock.alert.delete.mockRejectedValueOnce(new Error('Some Error')) // Actually is a prisma RecordNotFound Error
expect(removeAlert({}, {}, ctx)).rejects.toThrowError()
})
})
4 changes: 2 additions & 2 deletions helpers/controllers/alertController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const addAlert = async (
return alerts()
} catch (err) {
req.error(['Invalid data for alert creation', arg])
throw new Error(err)
throw err
}
}

Expand All @@ -45,6 +45,6 @@ export const removeAlert = async (
}
} catch (err) {
req.warn(['Error deleting alert', arg])
throw new Error(err)
throw err
}
}
2 changes: 1 addition & 1 deletion helpers/controllers/authController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ describe('auth controller', () => {
return expect(isTokenValid(null, userArgs)).resolves.toBe(false)
})
test('should throw error', () => {
prismaMock.user.findUnique.mockRejectedValue()
prismaMock.user.findUnique.mockRejectedValue(new Error('Some Error'))
return expect(isTokenValid(null, userArgs)).rejects.toThrowError()
})
})
Expand Down
207 changes: 95 additions & 112 deletions helpers/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,50 +19,43 @@ export const login = async (
ctx: Context
) => {
const { req } = ctx
try {
const { session } = req
const { username, password } = arg
const { session } = req
const { username, password } = arg

if (!session) {
throw new Error('Session Error')
}
if (!session) {
throw new Error('Session Error')
}

let user = await prisma.user.findFirst({ where: { username } })
// TODO change username column to be unique
// const user = await prisma.user.findUnique({ where: { username } })
if (!user) {
throw new UserInputError('User does not exist')
}
let user = await prisma.user.findFirst({ where: { username } })
// TODO change username column to be unique
// const user = await prisma.user.findUnique({ where: { username } })
if (!user) {
throw new UserInputError('User does not exist')
}

const validLogin = user.password
? await bcrypt.compare(password, user.password)
: false
if (!validLogin) {
throw new AuthenticationError('Password is invalid')
}
const validLogin = user.password
? await bcrypt.compare(password, user.password)
: false
if (!validLogin) {
throw new AuthenticationError('Password is invalid')
}

if (!user.cliToken) {
user = await prisma.user.update({
where: {
id: user.id
},
data: { cliToken: nanoid() }
})
}
if (!user.cliToken) {
user = await prisma.user.update({
where: {
id: user.id
},
data: { cliToken: nanoid() }
})
}

const cliToken = { id: user.id, cliToken: user.cliToken }
const cliToken = { id: user.id, cliToken: user.cliToken }

session.userId = user.id
return {
success: true,
username: user.username,
cliToken: encode(cliToken)
}
} catch (err) {
if (!err.extensions) {
req.error(err)
}
throw new Error(err)
session.userId = user.id
return {
success: true,
username: user.username,
cliToken: encode(cliToken)
}
}

Expand Down Expand Up @@ -98,104 +91,94 @@ export const signup = async (
ctx: Context
) => {
const { req } = ctx
try {
const { session } = req
const { firstName, lastName, username, email } = arg

if (!session) {
throw new Error('Session Error')
}
const { session } = req
const { firstName, lastName, username, email } = arg

const validEntry = await signupValidation.isValid({
firstName,
lastName,
username,
email
})
if (!session) {
throw new Error('Session Error')
}

if (!validEntry) {
throw new UserInputError('Register form is not completely filled out')
}
const validEntry = await signupValidation.isValid({
firstName,
lastName,
username,
email
})

// Check for existing user or email
const existingUser = await prisma.user.findFirst({
where: {
username
}
})
if (!validEntry) {
throw new UserInputError('Register form is not completely filled out')
}

if (existingUser) {
throw new UserInputError('User already exists')
// Check for existing user or email
const existingUser = await prisma.user.findFirst({
where: {
username
}
})

const existingEmail = await prisma.user.findFirst({
where: {
email
}
})
if (existingUser) {
throw new UserInputError('User already exists')
}

if (existingEmail) {
throw new UserInputError('Email already exists')
const existingEmail = await prisma.user.findFirst({
where: {
email
}
})

const name = `${firstName} ${lastName}`
if (existingEmail) {
throw new UserInputError('Email already exists')
}

let newUser = await prisma.user.create({
data: {
name,
username,
email
}
})
const name = `${firstName} ${lastName}`

const forgotToken = encode({
userId: newUser.id,
userToken: nanoid()
})
let newUser = await prisma.user.create({
data: {
name,
username,
email
}
})

const tokenExpiration = new Date(Date.now() + THREE_DAYS)
const forgotToken = encode({
userId: newUser.id,
userToken: nanoid()
})

newUser = await prisma.user.update({
where: {
id: newUser.id
},
data: {
forgotToken,
tokenExpiration
}
})
const tokenExpiration = new Date(Date.now() + THREE_DAYS)

newUser = await prisma.user.update({
where: {
id: newUser.id
},
data: {
forgotToken,
tokenExpiration
}
})

try {
await sendSignupEmail(email, forgotToken)
} catch (error) {
req.error(`
try {
await sendSignupEmail(email, forgotToken)
} catch (error) {
req.error(`
Error while sending signup email
${JSON.stringify(error, null, 2)}
`)
}
}

return {
success: true,
username: newUser.username,
cliToken: forgotToken
}
} catch (err) {
if (!err.extensions) {
req.error(err)
}
throw new Error(err)
return {
success: true,
username: newUser.username,
cliToken: forgotToken
}
}

export const isTokenValid = async (
_parent: void,
arg: { cliToken: string }
) => {
try {
const { id, cliToken } = decode(arg.cliToken)
const user = await prisma.user.findUnique({ where: { id } })
return user?.cliToken === cliToken || false
} catch (err) {
throw new Error(err)
}
const { id, cliToken } = decode(arg.cliToken)
const user = await prisma.user.findUnique({ where: { id } })
return user?.cliToken === cliToken || false
}
34 changes: 14 additions & 20 deletions helpers/controllers/challengesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,11 @@ export const createChallenge = async (
ctx: Context
) => {
const { req } = ctx
try {
isAdminOrThrow(req)
await validateLessonId(arg.lessonId)
await prisma.challenge.create({ data: arg })
return lessons()
} catch (err) {
throw new Error(err)
}

isAdminOrThrow(req)
await validateLessonId(arg.lessonId)
await prisma.challenge.create({ data: arg })
return lessons()
}

export const updateChallenge = async (
Expand All @@ -30,16 +27,13 @@ export const updateChallenge = async (
ctx: Context
) => {
const { req } = ctx
try {
isAdminOrThrow(req)
const { id, lessonId, ...data } = arg
await validateLessonId(lessonId)
await prisma.challenge.update({
where: { id },
data
})
return lessons()
} catch (err) {
throw new Error(err)
}

isAdminOrThrow(req)
const { id, lessonId, ...data } = arg
await validateLessonId(lessonId)
await prisma.challenge.update({
where: { id },
data
})
return lessons()
}
4 changes: 1 addition & 3 deletions helpers/controllers/passwordController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe('Request Password Reset', () => {
reqPwReset(() => {}, { userOrEmail: 'badc0d3r' }, ctx)
).rejects.toThrowError('User does not exist')
})
test('It should log the error if an internal function fails', async () => {
test('It should throw an error if an internal function fails', async () => {
prismaMock.user.findFirst.mockRejectedValue(new Error())
const errFunc = jest.fn()
await expect(
Expand All @@ -73,8 +73,6 @@ describe('Request Password Reset', () => {
{ req: { error: errFunc } }
)
).rejects.toThrowError()

expect(errFunc).toBeCalled()
})

it('should fail if email is not sent correctly', () => {
Expand Down
Loading

1 comment on commit 4b140cb

@vercel
Copy link

@vercel vercel bot commented on 4b140cb Oct 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.