Skip to content

Commit

Permalink
Merge pull request #140 from Code-Hammers/CHE-171/subtask/Refactor-Ca…
Browse files Browse the repository at this point in the history
…tch-All-Route-Handler

[CHE-171] Refactor Catch All Route Handler
  • Loading branch information
brok3turtl3 authored Jun 11, 2024
2 parents 061e069 + 16d2fbc commit b5850de
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 19 deletions.
16 changes: 10 additions & 6 deletions __tests__/errorController.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import app from '../server/index';
import request from 'supertest';
import { Request, Response, NextFunction } from 'express';
import { notFound } from '../server/controllers/errorControllers';
import errorHandler from '../server/middleware/errorHandler';
import { BadRequestError } from '../server/errors';
import { BadRequestError, NotFoundError } from '../server/errors';

describe('Middleware Tests', () => {
let mockRequest: Partial<Request>;
Expand All @@ -18,10 +19,13 @@ describe('Middleware Tests', () => {
});

describe('notFound Middleware', () => {
it('should return 404 and the original URL', () => {
notFound(mockRequest as Request, mockResponse as Response, mockNext);
expect(mockResponse.status).toHaveBeenCalledWith(404);
expect(mockNext).toHaveBeenCalled();
it('should return 404 and the original URL', async () => {
const exampleNotFoundError = new NotFoundError();

const response = await request(app).get('/non-existent-route').send();

expect(response.status).toEqual(404);
expect(response.body).toEqual(exampleNotFoundError.serializeErrors());
});
});

Expand Down
9 changes: 0 additions & 9 deletions server/controllers/errorControllers.ts

This file was deleted.

10 changes: 6 additions & 4 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import devRoutes from './routes/devRoutes';
import connectDB from './config/db';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import { notFound } from './controllers/errorControllers';
import errorHandler from './middleware/errorHandler';
import { NotFoundError } from './errors';

dotenv.config();

Expand All @@ -21,8 +21,6 @@ const app: Application = express();
app.use(express.json());
app.use(cookieParser());

connectDB();

app.get('/health', (req: Request, res: Response) => {
res.status(200).send('OK');
});
Expand All @@ -49,13 +47,17 @@ if (process.env.NODE_ENV === 'production') {
});
}

app.use(notFound);
app.use((_req, _res) => {
throw new NotFoundError();
});

app.use(errorHandler);

const PORT: number = Number(process.env.PORT) || 3000;

export const startServer = () => {
connectDB();

return app.listen(PORT, () =>
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`),
);
Expand Down

0 comments on commit b5850de

Please sign in to comment.