Skip to content

Commit

Permalink
chore: more changes
Browse files Browse the repository at this point in the history
  • Loading branch information
shihabmridha committed Jun 28, 2023
1 parent bc3d8f9 commit 6ddbc8e
Show file tree
Hide file tree
Showing 15 changed files with 155 additions and 171 deletions.
4 changes: 2 additions & 2 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ steps:
npm install
displayName: 'Installing dependencies'
- script: NODE_ENV=$(NODE_ENV) LOG_LEVEL=debug DB_PWD=$(DB_PASSWORD) DB_USER=$(DB_USERNAME) DB_HOST=$(DB_HOST) DB_NAME=$(DB_NAME) ./node_modules/.bin/jest --forceExit
- script: NODE_ENV=$(NODE_ENV) DB_PWD=$(DB_PASSWORD) DB_USER=$(DB_USERNAME) DB_HOST=$(DB_HOST) DB_NAME=$(DB_NAME) npm run test
displayName: 'Running tests'

- task: PublishTestResults@2
Expand All @@ -20,7 +20,7 @@ steps:
testRunner: JUnit
testResultsFiles: '**/test-report.xml'

- script: NODE_ENV=$(NODE_ENV) LOG_LEVEL=debug DB_PWD=$(DB_PASSWORD) DB_USER=$(DB_USERNAME) DB_HOST=$(DB_HOST) DB_NAME=$(DB_NAME) ./node_modules/.bin/jest --coverage --forceExit
- script: NODE_ENV=$(NODE_ENV) DB_PWD=$(DB_PASSWORD) DB_USER=$(DB_USERNAME) DB_HOST=$(DB_HOST) DB_NAME=$(DB_NAME) npm run test:cov
displayName: 'Running test coverage'
condition: succeededOrFailed()

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"start": "node ./src/app.ts",
"start:dev": "nodemon ./src/app.ts",
"start:prod": "node ./build/src/app.js",
"test": "jest --forceExit",
"test": "jest --runInBand --forceExit --no-cache",
"test:cov": "jest --coverage --forceExit",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix"
},
Expand All @@ -33,6 +33,7 @@
"@types/cors": "2.8.6",
"@types/dotenv": "8.2.0",
"@types/express": "4.17.17",
"@types/faker": "^6.6.9",
"@types/jest": "^25.2.3",
"@types/mongodb": "3.5.20",
"@types/node": "10.12.9",
Expand Down
123 changes: 61 additions & 62 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,81 @@
import { install as installSourceMapSupport } from 'source-map-support';
installSourceMapSupport();
// import { install as installSourceMapSupport } from 'source-map-support';
// installSourceMapSupport();
import 'reflect-metadata';
import * as dotenv from 'dotenv';
dotenv.config();

import * as express from 'express';
import * as compress from 'compression';
import * as cors from 'cors';
import app from './server';
import errorHandler from './common/errors/error.handler';
import errorHandler from './core/error.handler';
import logger from './core/logger';
import initDB from './core/database';
import database from './core/database';
import container from './core/inversify';
import ApplicationRouter from './router';

/**
* This is a bootstrap function
*/
async function bootstrap() {
// Attach HTTP request info logger middleware in test mode
if (process.env.NODE_ENV === 'test') {
app.use((req: express.Request, _res, next) => {
logger.debug(`[${req.method}] ${req.hostname}${req.url}`);
const app = express();

next();
});
}
app.disable('x-powered-by');
app.use(compress());

app.disable('x-powered-by');
app.use(compress());
// Enable middleware/whatever only in Production
if (process.env.NODE_ENV === 'production') {
// For example: Enable sentry in production
// app.use(Sentry.Handlers.requestHandler());
}

// Enable middleware/whatever only in Production
if (process.env.NODE_ENV === 'production') {
// For example: Enable sentry in production
// app.use(Sentry.Handlers.requestHandler());
}
/**
* Configure cors
*/
app.use(cors());

/**
* Configure cors
*/
app.use(cors());
/**
* Configure database
**/
if (!database.isConnected()) {
database
.connect()
.then(() => {
database.emit('connected');
logger.info('Database connected');
})
.catch((err) => {
logger.error('Database connection error', err);
});
}

/**
* Configure database
**/
if (!initDB.isDbConnected()) {
await initDB.connect();
}
/**
* Configure body parser
*/
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

/**
* Configure body parser
*/
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
/**
* Host static public directory
*/
app.use('/', express.static('public'));

/**
* Host static public directory
*/
app.use('/', express.static('public'));
/**
* Configure routes
*/
// Let inversify resolve the dependency
const router = container.get<ApplicationRouter>(ApplicationRouter);
router.register(app);

/**
* Configure routes
*/
// Let inversify resolve the dependency
const router = container.get<ApplicationRouter>(ApplicationRouter);
router.register(app);
/**
* Configure error handler
*/
errorHandler(app);

/**
* Configure error handler
*/
errorHandler(app);
}
/**
* Setup listener port
*/
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
logger.info(`Running Node.js version ${process.version}`);
logger.info(`App environment: ${process.env.NODE_ENV}`);
logger.info(`App is running on port ${PORT}`);
});

// Need for integration testing
export default app;

// Invoking the bootstrap function
bootstrap()
.then(() => {
logger.info('Server is up');
})
.catch((error) => {
logger.error('Unknown error. ' + error.message);
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Constants from '../constants';
import Constants from './constants';

export class ApplicationError extends Error {
public code = null;
Expand Down
55 changes: 26 additions & 29 deletions src/common/test.helper.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
import * as faker from 'faker';
import log from '../core/logger';
import Repository from '../core/repository';
import UserRepository, { UserDocument } from '../user/user.repository';

if (process.env.NODE_ENV !== 'test') {
log.error('Invalid environment for tests');
process.exit(1);
import db from '../core/database';
import UserRepository from '../user/user.repository';
import logger from '../core/logger';

export function testPreparation() {
beforeEach(async () => {
try {
if (db.isConnected()) {
await clearDatabase();
}
} catch (error) {
logger.log('error', error.message);
}
});

beforeAll((done) => {
if (db.isConnected()) {
done();
} else {
db.on('connected', async () => {
await clearDatabaseIndices();
done();
});
}
});
}

let userRepository: Repository<UserDocument>;
const userRepository = new UserRepository();

async function clearDatabase() {
await userRepository.remove({}, true);
Expand All @@ -18,27 +36,6 @@ async function clearDatabaseIndices() {
await userRepository.getCollection().dropIndexes();
}

beforeEach(async () => {
try {
await clearDatabase();
} catch (error) {
log.info(error.message);
}
});

beforeAll(async () => {
try {
// Wait for Jest to run the app and connect to database
await new Promise((resolve) => setTimeout(resolve, 5000));

userRepository = new UserRepository();

await clearDatabaseIndices();
} catch (error) {
log.info(error.message);
}
});

export async function createUser(
username?: string,
email?: string,
Expand Down
2 changes: 1 addition & 1 deletion src/common/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ObjectId } from 'mongodb';
import { InvalidIdError } from '../errors/app.errors';
import { InvalidIdError } from '../app.errors';

export function getValidObjectId(id: string | ObjectId) {
if (!ObjectId.isValid(id)) {
Expand Down
12 changes: 0 additions & 12 deletions src/core/database.test.ts

This file was deleted.

27 changes: 15 additions & 12 deletions src/core/database.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
import { MongoClient, Db, Collection, ServerApiVersion } from 'mongodb';
import { EventEmitter } from 'events';
import logger from './logger';

/**
* All the methods and properties mentioned in the following class is
* specific to MongoDB. You should make necessary changes to support
* the database/orm you want to use.
*/
class Database {
class Database extends EventEmitter {
private password: string;

private user: string;

private host: string;

private dbName: string;

private dbClient: MongoClient;

private databaseInstance: Db;
private mongoProtocol = 'mongodb';

constructor() {
super();

this.password = process.env.DB_PWD;
this.user = process.env.DB_USER;
this.host = process.env.DB_HOST;
this.dbName = process.env.DB_NAME;

if (process.env.MONGO_PROTOCOL) {
this.mongoProtocol = process.env.MONGO_PROTOCOL;
}
}

public async connect(): Promise<void> {
Expand Down Expand Up @@ -98,26 +101,26 @@ class Database {
* Customize as needed for your database.
*/
private getConnectionString() {
return `mongodb://${this.user}:${this.password}@${this.host}/${this.dbName}`;
return `${this.mongoProtocol}://${this.user}:${this.password}@${this.host}/${this.dbName}`;
}

public getDbHost() {
public getHost() {
return this.host;
}

public getDbPassword() {
public getPassword() {
return this.password;
}

public getDbUser() {
public getUser() {
return this.user;
}

public getDbName() {
public getName() {
return this.dbName;
}

public isDbConnected() {
public isConnected() {
return Boolean(this.dbClient);
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/common/errors/error.handler.ts → src/core/error.handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Application, Request, Response, NextFunction } from 'express';
import { NotFoundError, ApplicationError } from './app.errors';
import { NotFoundError, ApplicationError } from '../common/app.errors';
import { MongoError } from 'mongodb';
import log from '../../core/logger';
import log from './logger';

export default function (app: Application) {
// If you are lost
Expand All @@ -12,21 +12,21 @@ export default function (app: Application) {
// Request error handler
app.use(
(
err: ApplicationError,
error: ApplicationError,
_req: Request,
res: Response,
next: NextFunction,
) => {
if (err instanceof ApplicationError) {
if (err.message) {
log.info(err.message);
return res.status(err.code).send(err.message);
if (error instanceof ApplicationError) {
log.error(error?.message, error.stack);
if (error.message) {
return res.status(error.code).send(error.message);
} else {
return res.sendStatus(err.code);
return res.sendStatus(error.code);
}
}

next(err);
next(error);
},
);

Expand Down Expand Up @@ -67,7 +67,7 @@ export default function (app: Application) {
});

// Optional fallthrough error handler
app.use(function onError(
app.use(function (
err: Error,
_req: Request,
res: Response,
Expand Down
Loading

0 comments on commit 6ddbc8e

Please sign in to comment.