Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error Handler stopped working #36

Merged
merged 2 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/errorHandler/handlerForExpress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,33 @@ export const errorLogger = (
response: Response,
next: NextFunction,
) => {
console.log(`error ${error.message}`);
next(error); // calling next middleware
console.log(`Caught Error: ${error.message}`);
return next(error);
};

// Error handling Middleware function reads the error message
// and sends back a response in JSON format
export const errorResponder = (error: Error, request: Request, response: Response) => {
response.header('Content-Type', 'application/json');
if (error instanceof BaseError) {
response.status(error.status).send(error.message);
export const errorResponder = (
error: Error,
request: Request,
response: Response,
next: NextFunction,
) => {
if (error) {
response.header('Content-Type', 'application/json');
if (error instanceof BaseError) {
response.status(error.status).send({ message: error.message });
} else {
response.status(500).send({ message: 'Something went wrong' });
}
} else {
response.status(500).send('Something went wrong');
next();
}
};

// Fallback Middleware function for returning
// 404 error for undefined paths
export const invalidPathHandler = (request: Request, response: Response) => {
response.status(404);
response.send('invalid path');
response.send('Invalid path');
};
10 changes: 3 additions & 7 deletions src/firebase/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function createUser(newUser: BeforeCreateUser): Promise<User> {
const emailQuery = query(collection(db, 'users'), where('email', '==', newUser.email));
const emailQuerySnapshot = await getDocs(emailQuery);
if (!emailQuerySnapshot.empty) {
throw new BaseError('That email is already in the system', 400);
throw new BaseError('That email is already in the system', 400);
}
const hashedPassword: string = await bcrypt.hash(newUser.password!, 10);
const docRef = doc(collection(db, `users`));
Expand Down Expand Up @@ -89,11 +89,7 @@ export async function getUserByToken(id: string): Promise<User> {
return user as User;
}

export async function userLogin(
email: string,
password: string,
orgId: string,
): Promise<{ user: User }> {
export async function userLogin(email: string, password: string, orgId: string): Promise<User> {
const emailQuery = query(collection(db, 'users'), where('email', '==', email));
const emailQuerySnapshot = await getDocs(emailQuery);

Expand All @@ -117,7 +113,7 @@ export async function userLogin(
if (!user) {
throw new BaseError('User not found', 404);
}
return { user };
return user;
}
}
throw new BaseError('User did not complete the login because something was spelt wrong!', 401);
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ app.use('/users', userRoutes);
app.get('/', (req: Request, res: Response) => {
res.send('Hello, this is the backend.');
});

// Catch celebrate validation errors
app.use(errors());

Expand Down
41 changes: 28 additions & 13 deletions src/jest/users.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ describe('FIREBASE User tests', () => {
beforeAll(async () => {
testUser = await createUser(createTestUser);
});

test('Successfully create a user in the FIREBASE User service', async () => {
expect(testUser.firstName).toBe(createTestUser.firstName);
expect(testUser.lastName).toBe(createTestUser.lastName);
expect(testUser.email).toBe(createTestUser.email);
expect(testUser.orgId).toStrictEqual(createTestUser.orgId);
});

test('Successfully retrieve a user by organization ID from the FIREBASE User service', async () => {
const data = await getAllUsersByOrgId(testUser.orgId![0]);
const corretId = data.find((e) => e.id === testUser.id);
Expand All @@ -46,17 +48,18 @@ describe('FIREBASE User tests', () => {
expect(data.email).toBe(testUser.email);
expect(data.orgId).toStrictEqual(testUser.orgId);
});

test('Successfully log in a user via the FIREBASE User service', async () => {
const data = await userLogin(
testUser.email,
createTestUser.password as string,
testUser.orgId![0].toString(),
);
expect(data.user.firstName).toBe(testUser.firstName);
expect(data.user.lastName).toBe(testUser.lastName);
expect(data.user.email).toBe(testUser.email);
expect(data.user.orgId[0]).toStrictEqual(testUser.orgId);
expect(data.user.id).toBe(testUser.id);
expect(data.firstName).toBe(testUser.firstName);
expect(data.lastName).toBe(testUser.lastName);
expect(data.email).toBe(testUser.email);
expect(data.orgId[0]).toStrictEqual(testUser.orgId);
expect(data.id).toBe(testUser.id);
});

test('Successfully delete a user from the FIREBASE User service', async () => {
Expand All @@ -68,7 +71,6 @@ describe('FIREBASE User tests', () => {
/******************/
/**** Express ****/
/******************/

describe('EXPRESS user routes', () => {
let expressId: string;
let expressToken: string;
Expand All @@ -92,6 +94,7 @@ describe('EXPRESS user routes', () => {
expect(res.body.email).toBe(user1.email);
expect(res.body).not.toHaveProperty('password');
});

test('Successfully log in a user via the EXPRESS user route', async () => {
const res = await request(app)
.post('/users/' + orgid + '/login')
Expand All @@ -101,11 +104,12 @@ describe('EXPRESS user routes', () => {
})
.set('Authorization', 'Bearer ' + expressToken);
expect(res.statusCode).toBe(200);
expect(res.body.user.firstName).toBe(user1.firstName);
expect(res.body.user.lastName).toBe(user1.lastName);
expect(res.body.user.email).toBe(user1.email);
expect(res.body.firstName).toBe(user1.firstName);
expect(res.body.lastName).toBe(user1.lastName);
expect(res.body.email).toBe(user1.email);
expect(res.body).not.toHaveProperty('password');
});

test('Get user by orgId', async () => {
const res = await request(app)
.get('/users/' + orgid)
Expand All @@ -117,6 +121,7 @@ describe('EXPRESS user routes', () => {
expect(user.email).toBe(user1.email);
expect(res.body).not.toHaveProperty('password');
});

test('Successfully retrieve a user by token from the EXPRESS user route', async () => {
const res = await request(app)
.get('/users/' + orgid + '/me')
Expand All @@ -127,12 +132,14 @@ describe('EXPRESS user routes', () => {
expect(res.body.email).toBe(user1.email);
expect(res.body).not.toHaveProperty('password');
});

const user2: { [key: string]: any } = {
firstName: 'Thor',
lastName: 'Hansen',
email: '[email protected]',
password: 'Testå123Å4!!!!!',
};

test('Successfully update a user via the EXPRESS user route', async () => {
const res = await request(app)
.put('/users/' + orgid + '/' + expressId)
Expand All @@ -144,6 +151,7 @@ describe('EXPRESS user routes', () => {
expect(res.body.email).toBe(user2.email);
expect(res.body).not.toHaveProperty('password');
});

test('Successfully log in a user after password change via the EXPRESS user route', async () => {
const res = await request(app)
.post('/users/' + orgid + '/login')
Expand All @@ -153,11 +161,12 @@ describe('EXPRESS user routes', () => {
})
.set('Authorization', 'Bearer ' + expressToken);
expect(res.statusCode).toBe(200);
expect(res.body.user.firstName).toBe(user2.firstName);
expect(res.body.user.lastName).toBe(user2.lastName);
expect(res.body.user.email).toBe(user2.email);
expect(res.body.firstName).toBe(user2.firstName);
expect(res.body.lastName).toBe(user2.lastName);
expect(res.body.email).toBe(user2.email);
expect(res.body).not.toHaveProperty('password');
});

test('Delete user', async () => {
const res = await request(app)
.delete('/users/' + orgid + '/' + expressId)
Expand Down Expand Up @@ -205,8 +214,10 @@ describe('Test meant to fail', () => {
});
expect(res.statusCode).toBe(400);
});

const userWithTokenPassword = 'Asd!!!asdD23123';
let userWithToken: User;

test('Fail to create a user with an existing email via the EXPRESS user route', async () => {
const res1 = await request(app)
.post('/users/' + orgId)
Expand All @@ -225,9 +236,11 @@ describe('Test meant to fail', () => {
email: '[email protected]',
password: 'Asd!!!asdD23123',
});

expect(res1.statusCode).toBe(201);
expect(res2.statusCode).toBe(400);
});

test('Fail to authenticate a user with an incorrect password via the EXPRESS user route', async () => {
const res = await request(app)
.post('/users/' + orgId + '/login')
Expand Down Expand Up @@ -258,12 +271,14 @@ describe('Test meant to fail', () => {
expect(res.statusCode).toBe(401);
await deleteUser(userWithToken);
});

test('Fail to fetch user details by organization ID with an invalid token via the EXPRESS user route', async () => {
const res = await request(app)
.post('/users/' + orgId + '/me')
.set('Authorization', 'Bearer ' + 'wrongToken');
expect(res.statusCode).toBe(500);
expect(res.statusCode).toBe(404);
});

test('Fail to create a user with inconsistent repeat password via the EXPRESS user route', async () => {
const res = await request(app)
.post('/users/' + orgId)
Expand Down
20 changes: 15 additions & 5 deletions src/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import { BaseError } from '../errorHandler/baseErrors';

const router = Router();

// create new
/**********************/
/** CREATE NEW EVENT **/
/**********************/
router.post(
'/:orgId/',
celebrate({
Expand All @@ -41,7 +43,9 @@ router.post(
}),
);

// get all
/**********************/
/*** GET ALL EVENTS ***/
/**********************/
router.get(
'/:orgId/',
asyncHandler(async (req: Request, res: Response) => {
Expand All @@ -50,7 +54,9 @@ router.get(
}),
);

//get by id
/**********************/
/***** GET BY ID ******/
/**********************/
router.get(
'/:orgId/:id',
asyncHandler(async (req: Request, res: Response) => {
Expand All @@ -63,7 +69,9 @@ router.get(
}),
);

//update
/**********************/
/**** UPDATE EVENT ****/
/**********************/
router.put(
'/:orgId/:id',
celebrate({
Expand Down Expand Up @@ -93,7 +101,9 @@ router.put(
}),
);

// delete by id
/**********************/
/**** DELETE EVENT ****/
/**********************/
router.delete(
'/:orgId/:id',
auth,
Expand Down
Loading