Skip to content

Commit 4b140cb

Browse files
authored
Merge pull request #1162 from tomrule007/refactor/trycatch-unknown
Refactor/try catch unknown
2 parents 909a976 + eda2552 commit 4b140cb

File tree

9 files changed

+180
-221
lines changed

9 files changed

+180
-221
lines changed

helpers/admin/adminHelpers.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { reach } from 'yup'
1+
import { reach, ValidationError } from 'yup'
22
import _ from 'lodash'
33
import { DROP_DOWN, TEXT_AREA, MD_INPUT } from '../../components/FormCard'
44

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

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

112-
inner.forEach((innerObj: any, errorIndex: number) => {
112+
inner.forEach((innerObj, errorIndex) => {
113113
// get index of property with title equal to value of innerObj.path
114114
const titleIndex = properties.findIndex(
115115
(property: any) => property.title === innerObj.path

helpers/controllers/alertController.test.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,7 @@ describe('Alert controller tests', () => {
5353
expect(removeAlert({}, { id: 5 }, ctx)).resolves.toEqual({ success: true })
5454
})
5555
test('Should throw error if no id provided when removing alert', async () => {
56-
prismaMock.alert.delete.mockRejectedValueOnce('No alert id provided')
57-
expect(removeAlert({}, {}, ctx)).rejects.toThrowError(
58-
'No alert id provided'
59-
)
56+
prismaMock.alert.delete.mockRejectedValueOnce(new Error('Some Error')) // Actually is a prisma RecordNotFound Error
57+
expect(removeAlert({}, {}, ctx)).rejects.toThrowError()
6058
})
6159
})

helpers/controllers/alertController.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export const addAlert = async (
2626
return alerts()
2727
} catch (err) {
2828
req.error(['Invalid data for alert creation', arg])
29-
throw new Error(err)
29+
throw err
3030
}
3131
}
3232

@@ -45,6 +45,6 @@ export const removeAlert = async (
4545
}
4646
} catch (err) {
4747
req.warn(['Error deleting alert', arg])
48-
throw new Error(err)
48+
throw err
4949
}
5050
}

helpers/controllers/authController.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ describe('auth controller', () => {
203203
return expect(isTokenValid(null, userArgs)).resolves.toBe(false)
204204
})
205205
test('should throw error', () => {
206-
prismaMock.user.findUnique.mockRejectedValue()
206+
prismaMock.user.findUnique.mockRejectedValue(new Error('Some Error'))
207207
return expect(isTokenValid(null, userArgs)).rejects.toThrowError()
208208
})
209209
})

helpers/controllers/authController.ts

Lines changed: 95 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -19,50 +19,43 @@ export const login = async (
1919
ctx: Context
2020
) => {
2121
const { req } = ctx
22-
try {
23-
const { session } = req
24-
const { username, password } = arg
22+
const { session } = req
23+
const { username, password } = arg
2524

26-
if (!session) {
27-
throw new Error('Session Error')
28-
}
25+
if (!session) {
26+
throw new Error('Session Error')
27+
}
2928

30-
let user = await prisma.user.findFirst({ where: { username } })
31-
// TODO change username column to be unique
32-
// const user = await prisma.user.findUnique({ where: { username } })
33-
if (!user) {
34-
throw new UserInputError('User does not exist')
35-
}
29+
let user = await prisma.user.findFirst({ where: { username } })
30+
// TODO change username column to be unique
31+
// const user = await prisma.user.findUnique({ where: { username } })
32+
if (!user) {
33+
throw new UserInputError('User does not exist')
34+
}
3635

37-
const validLogin = user.password
38-
? await bcrypt.compare(password, user.password)
39-
: false
40-
if (!validLogin) {
41-
throw new AuthenticationError('Password is invalid')
42-
}
36+
const validLogin = user.password
37+
? await bcrypt.compare(password, user.password)
38+
: false
39+
if (!validLogin) {
40+
throw new AuthenticationError('Password is invalid')
41+
}
4342

44-
if (!user.cliToken) {
45-
user = await prisma.user.update({
46-
where: {
47-
id: user.id
48-
},
49-
data: { cliToken: nanoid() }
50-
})
51-
}
43+
if (!user.cliToken) {
44+
user = await prisma.user.update({
45+
where: {
46+
id: user.id
47+
},
48+
data: { cliToken: nanoid() }
49+
})
50+
}
5251

53-
const cliToken = { id: user.id, cliToken: user.cliToken }
52+
const cliToken = { id: user.id, cliToken: user.cliToken }
5453

55-
session.userId = user.id
56-
return {
57-
success: true,
58-
username: user.username,
59-
cliToken: encode(cliToken)
60-
}
61-
} catch (err) {
62-
if (!err.extensions) {
63-
req.error(err)
64-
}
65-
throw new Error(err)
54+
session.userId = user.id
55+
return {
56+
success: true,
57+
username: user.username,
58+
cliToken: encode(cliToken)
6659
}
6760
}
6861

@@ -98,104 +91,94 @@ export const signup = async (
9891
ctx: Context
9992
) => {
10093
const { req } = ctx
101-
try {
102-
const { session } = req
103-
const { firstName, lastName, username, email } = arg
10494

105-
if (!session) {
106-
throw new Error('Session Error')
107-
}
95+
const { session } = req
96+
const { firstName, lastName, username, email } = arg
10897

109-
const validEntry = await signupValidation.isValid({
110-
firstName,
111-
lastName,
112-
username,
113-
email
114-
})
98+
if (!session) {
99+
throw new Error('Session Error')
100+
}
115101

116-
if (!validEntry) {
117-
throw new UserInputError('Register form is not completely filled out')
118-
}
102+
const validEntry = await signupValidation.isValid({
103+
firstName,
104+
lastName,
105+
username,
106+
email
107+
})
119108

120-
// Check for existing user or email
121-
const existingUser = await prisma.user.findFirst({
122-
where: {
123-
username
124-
}
125-
})
109+
if (!validEntry) {
110+
throw new UserInputError('Register form is not completely filled out')
111+
}
126112

127-
if (existingUser) {
128-
throw new UserInputError('User already exists')
113+
// Check for existing user or email
114+
const existingUser = await prisma.user.findFirst({
115+
where: {
116+
username
129117
}
118+
})
130119

131-
const existingEmail = await prisma.user.findFirst({
132-
where: {
133-
email
134-
}
135-
})
120+
if (existingUser) {
121+
throw new UserInputError('User already exists')
122+
}
136123

137-
if (existingEmail) {
138-
throw new UserInputError('Email already exists')
124+
const existingEmail = await prisma.user.findFirst({
125+
where: {
126+
email
139127
}
128+
})
140129

141-
const name = `${firstName} ${lastName}`
130+
if (existingEmail) {
131+
throw new UserInputError('Email already exists')
132+
}
142133

143-
let newUser = await prisma.user.create({
144-
data: {
145-
name,
146-
username,
147-
email
148-
}
149-
})
134+
const name = `${firstName} ${lastName}`
150135

151-
const forgotToken = encode({
152-
userId: newUser.id,
153-
userToken: nanoid()
154-
})
136+
let newUser = await prisma.user.create({
137+
data: {
138+
name,
139+
username,
140+
email
141+
}
142+
})
155143

156-
const tokenExpiration = new Date(Date.now() + THREE_DAYS)
144+
const forgotToken = encode({
145+
userId: newUser.id,
146+
userToken: nanoid()
147+
})
157148

158-
newUser = await prisma.user.update({
159-
where: {
160-
id: newUser.id
161-
},
162-
data: {
163-
forgotToken,
164-
tokenExpiration
165-
}
166-
})
149+
const tokenExpiration = new Date(Date.now() + THREE_DAYS)
150+
151+
newUser = await prisma.user.update({
152+
where: {
153+
id: newUser.id
154+
},
155+
data: {
156+
forgotToken,
157+
tokenExpiration
158+
}
159+
})
167160

168-
try {
169-
await sendSignupEmail(email, forgotToken)
170-
} catch (error) {
171-
req.error(`
161+
try {
162+
await sendSignupEmail(email, forgotToken)
163+
} catch (error) {
164+
req.error(`
172165
Error while sending signup email
173166
${JSON.stringify(error, null, 2)}
174167
`)
175-
}
168+
}
176169

177-
return {
178-
success: true,
179-
username: newUser.username,
180-
cliToken: forgotToken
181-
}
182-
} catch (err) {
183-
if (!err.extensions) {
184-
req.error(err)
185-
}
186-
throw new Error(err)
170+
return {
171+
success: true,
172+
username: newUser.username,
173+
cliToken: forgotToken
187174
}
188175
}
189176

190177
export const isTokenValid = async (
191178
_parent: void,
192179
arg: { cliToken: string }
193180
) => {
194-
try {
195-
const { id, cliToken } = decode(arg.cliToken)
196-
const user = await prisma.user.findUnique({ where: { id } })
197-
return user?.cliToken === cliToken || false
198-
} catch (err) {
199-
throw new Error(err)
200-
}
181+
const { id, cliToken } = decode(arg.cliToken)
182+
const user = await prisma.user.findUnique({ where: { id } })
183+
return user?.cliToken === cliToken || false
201184
}

helpers/controllers/challengesController.ts

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,11 @@ export const createChallenge = async (
1414
ctx: Context
1515
) => {
1616
const { req } = ctx
17-
try {
18-
isAdminOrThrow(req)
19-
await validateLessonId(arg.lessonId)
20-
await prisma.challenge.create({ data: arg })
21-
return lessons()
22-
} catch (err) {
23-
throw new Error(err)
24-
}
17+
18+
isAdminOrThrow(req)
19+
await validateLessonId(arg.lessonId)
20+
await prisma.challenge.create({ data: arg })
21+
return lessons()
2522
}
2623

2724
export const updateChallenge = async (
@@ -30,16 +27,13 @@ export const updateChallenge = async (
3027
ctx: Context
3128
) => {
3229
const { req } = ctx
33-
try {
34-
isAdminOrThrow(req)
35-
const { id, lessonId, ...data } = arg
36-
await validateLessonId(lessonId)
37-
await prisma.challenge.update({
38-
where: { id },
39-
data
40-
})
41-
return lessons()
42-
} catch (err) {
43-
throw new Error(err)
44-
}
30+
31+
isAdminOrThrow(req)
32+
const { id, lessonId, ...data } = arg
33+
await validateLessonId(lessonId)
34+
await prisma.challenge.update({
35+
where: { id },
36+
data
37+
})
38+
return lessons()
4539
}

helpers/controllers/passwordController.test.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ describe('Request Password Reset', () => {
6363
reqPwReset(() => {}, { userOrEmail: 'badc0d3r' }, ctx)
6464
).rejects.toThrowError('User does not exist')
6565
})
66-
test('It should log the error if an internal function fails', async () => {
66+
test('It should throw an error if an internal function fails', async () => {
6767
prismaMock.user.findFirst.mockRejectedValue(new Error())
6868
const errFunc = jest.fn()
6969
await expect(
@@ -73,8 +73,6 @@ describe('Request Password Reset', () => {
7373
{ req: { error: errFunc } }
7474
)
7575
).rejects.toThrowError()
76-
77-
expect(errFunc).toBeCalled()
7876
})
7977

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

0 commit comments

Comments
 (0)