Skip to content

Commit

Permalink
Fix error middleware (#88)
Browse files Browse the repository at this point in the history
* fix(templates): will failing test fail ci

* fix(templates):  whitespace prettier

* fix(templates): test routes

* fix(templates): mock config.utils

* fix(templates): file name and location consistancy

* fix(templates): remove yarn lock

* fix(template tests): small fixes

---------

Co-authored-by: praveenkumarct <[email protected]>
  • Loading branch information
harm-meijer and praveenkumarct authored Sep 25, 2024
1 parent 5010723 commit e12d8a7
Show file tree
Hide file tree
Showing 43 changed files with 620 additions and 210 deletions.
33 changes: 33 additions & 0 deletions application-templates/javascript/event/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'dotenv/config';

import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import EventRoutes from './routes/event.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/event', EventRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
25 changes: 1 addition & 24 deletions application-templates/javascript/event/src/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,11 @@
import 'dotenv/config';

import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import EventRoutes from './routes/event.route.js';
import { logger } from './utils/logger.utils.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';

// Read env variables
readConfiguration();
import app from './app.js';

const PORT = 8080;

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/event', EventRoutes);

// Global error handler
app.use(errorMiddleware);

// Listen the application
const server = app.listen(PORT, () => {
logger.info(`⚡️ Event application listening on port ${PORT}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CustomError from '../errors/custom.error.js';

export const errorMiddleware = (error, _req, res) => {
export const errorMiddleware = (error, _req, res, _next) => {
const isDevelopment = process.env.NODE_ENV === 'development';

if (error instanceof CustomError) {
Expand All @@ -13,5 +13,11 @@ export const errorMiddleware = (error, _req, res) => {
return;
}

res.status(500).send(isDevelopment ? error : 'Internal server error');
res
.status(500)
.send(
isDevelopment
? { message: error.message }
: { message: 'Internal server error' }
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { post } from '../controllers/event.controller.js';

const eventRouter = Router();

eventRouter.post('/', (req, res, next) => {
eventRouter.post('/', async (req, res, next) => {
logger.info('Event message received');

try {
post(req, res);
await post(req, res);
} catch (error) {
next(error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const readConfiguration = jest.fn(() => ({
clientId: 'mockedClientId',
clientSecret: 'mockedClientSecret',
projectKey: 'mockedProjectKey',
scope: 'mockedScope',
region: 'mockedRegion',
}));
Original file line number Diff line number Diff line change
@@ -1,9 +1,61 @@
import { expect } from '@jest/globals';
import request from 'supertest';
import app from '../../src/app';
import * as eventController from '../../src/controllers/event.controller';
import { readConfiguration } from '../../src/utils/config.utils';

//@todo: test this with msw (see typescipt job)
// make msw a shared package
describe('Testing Event Controller', () => {
test('POST `/event` route', async () => {
expect(1).toBe(1);
jest.mock('../../src/utils/config.utils');
describe('Testing router', () => {
beforeEach(() => {
readConfiguration.mockClear();
});
test('Post to non existing route', async () => {
const response = await request(app).post('/none');
expect(response.status).toBe(404);
expect(response.body).toEqual({
message: 'Path not found.',
});
});

test('Post invalid body', async () => {
const response = await request(app).post('/event').send({
message: 'hello world',
});
expect(response.status).toBe(400);
expect(response.body).toEqual({
message: 'Bad request: No customer id in the Pub/Sub message',
});
});

test('Post empty body', async () => {
const response = await request(app).post('/event');
expect(response.status).toBe(400);
expect(response.body).toEqual({
message: 'Bad request: Wrong No Pub/Sub message format',
});
});
});

describe('unexpected error', () => {
let postMock;

beforeEach(() => {
// Mock the post method to throw an error
postMock = jest.spyOn(eventController, 'post').mockImplementation(() => {
throw new Error('Test error');
});
readConfiguration.mockClear();
});

test('should handle errors thrown by post method', async () => {
// Call the route handler
const response = await request(app).post('/event');
expect(response.status).toBe(500);
expect(response.body).toEqual({ message: 'Internal server error' });
});

afterEach(() => {
// Restore the original implementation
postMock.mockRestore();
});
});
29 changes: 29 additions & 0 deletions application-templates/javascript/job/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as dotenv from 'dotenv';
dotenv.config();

import express from 'express';

// Import routes
import JobRoutes from './routes/job.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define routes
app.use('/job', JobRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
22 changes: 1 addition & 21 deletions application-templates/javascript/job/src/index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,12 @@
import * as dotenv from 'dotenv';
dotenv.config();

import express from 'express';

// Import routes
import JobRoutes from './routes/job.route.js';

// Import logger
import { logger } from './utils/logger.utils.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';

// Read env variables
readConfiguration();
import app from './app.js';

const PORT = 8080;

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define routes
app.use('/job', JobRoutes);

// Global error handler
app.use(errorMiddleware);

// Listen the application
const server = app.listen(PORT, () => {
logger.info(`⚡️ Job application listening on port ${PORT}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CustomError from '../errors/custom.error.js';

export const errorMiddleware = (error, _req, res) => {
export const errorMiddleware = (error, _req, res, _next) => {
const isDevelopment = process.env.NODE_ENV === 'development';

if (error instanceof CustomError) {
Expand All @@ -13,5 +13,11 @@ export const errorMiddleware = (error, _req, res) => {
return;
}

res.status(500).send(isDevelopment ? error : 'Internal server error');
res
.status(500)
.send(
isDevelopment
? { messge: error.message }
: { message: 'Internal server error' }
);
};
4 changes: 2 additions & 2 deletions application-templates/javascript/job/src/routes/job.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { post } from '../controllers/job.controller.js';
// Create the router for our app
const jobRouter = Router();

jobRouter.post('/', (req, res, next) => {
jobRouter.post('/', async (req, res, next) => {
try {
post(req, res);
await post(req, res);
} catch (error) {
next(error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const readConfiguration = jest.fn(() => ({
clientId: 'mockedClientId',
clientSecret: 'mockedClientSecret',
projectKey: 'mockedProjectKey',
scope: 'mockedScope',
region: 'mockedRegion',
}));

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect } from '@jest/globals';
import request from 'supertest';
import app from '../../src/app';
import * as jobController from '../../src/controllers/job.controller';
import { readConfiguration } from '../../src/utils/config.utils';

jest.mock('../../src/utils/config.utils');
describe('Testing router', () => {
beforeEach(() => {
readConfiguration.mockClear();
});
test('Post to non existing route', async () => {
const response = await request(app).post('/none');
expect(response.status).toBe(404);
expect(response.body).toEqual({
message: 'Path not found.',
});
});
});
describe('unexpected error', () => {
let postMock;

beforeEach(() => {
// Mock the post method to throw an error
postMock = jest.spyOn(jobController, 'post').mockImplementation(() => {
throw new Error('Test error');
});
readConfiguration.mockClear();
});

afterEach(() => {
// Restore the original implementation
postMock.mockRestore();
});
test('should handle errors thrown by post method', async () => {
// Call the route handler
const response = await request(app).post('/job');
expect(response.status).toBe(500);
expect(response.body).toEqual({ message: 'Internal server error' });
});
});
32 changes: 32 additions & 0 deletions application-templates/javascript/service/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import 'dotenv/config';
import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import ServiceRoutes from './routes/service.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/service', ServiceRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
Loading

0 comments on commit e12d8a7

Please sign in to comment.