Rearranged and refactored main Api Class

This commit is contained in:
Alexis
2021-08-03 17:33:20 +02:00
parent 288432244b
commit fabe285fb2
2 changed files with 49 additions and 44 deletions

View File

@@ -1,5 +1,6 @@
import express, { Application } from 'express' import express, { Application } from 'express'
import { Connection } from 'typeorm' import { Connection } from 'typeorm'
import { VSColors } from '../enums/VSColors'
import { AuracleApiRouter } from './AuracleApiRouter' import { AuracleApiRouter } from './AuracleApiRouter'
export class AuracleApi { export class AuracleApi {
public app: Application public app: Application
@@ -21,24 +22,17 @@ export class AuracleApi {
// Making sure the DB is up before init routers, modules, etc... // Making sure the DB is up before init routers, modules, etc...
if (init.database) { if (init.database) {
this.db_connect(init.database) this.connectDatabase(init.database)
.then(() => { .then(async () => {
// Sets up tasks to execute... // Loads other services
const tasks = [ await this.registerServices(init.routers, init.modules, init.middlewares)
this.modules(init.modules),
this.routers(init.routers),
this.middlewares(init.middlewares)
]
Promise.all(tasks) this.listen()
.catch((err) => {
throw err
})
}) })
.catch((err) => { .catch((err) => {
console.error("App couldn't boot up with the following errors : ") console.error(VSColors.red, "[ERROR] App couldn't boot up with the following errors : ")
console.error(err) console.error(VSColors.red, err)
}) })
} }
} }
@@ -46,33 +40,53 @@ export class AuracleApi {
/** /**
* Links the API with a TypeORM connection * Links the API with a TypeORM connection
*/ */
private db_connect = async (db_driver: Promise<Connection>) => { private async connectDatabase(db_driver: Promise<Connection>) {
try { try {
// Tries to connect...
const connection = await db_driver const connection = await db_driver
console.info('Connection has been established successfully.') console.info(VSColors.cyan, '[INFO] Connection has been established successfully.')
// Builds the data schema from registered entities // Should the DB be rebuilt ? Are we in production ?
await connection.synchronize() const dropDatabase = (process.env.NODE_ENV === 'production') ? true : false
console.info('Database schemas have been generated successfully.')
// Then builds the data schema from registered entities...
await connection.synchronize(dropDatabase)
console.info(VSColors.cyan, '[INFO] Database schemas have been generated successfully.')
return connection return connection
} catch (err) { } catch (err) {
console.error('Unable to connect to the database.') console.error(VSColors.red, '[ERROR] Unable to connect to the database !')
throw err throw err
} }
} }
/**
* Registers other express services to add onto the core app
*
* @param routers A list of Express Routers extended from AuracleApiRouter
* @param modules A list of Express extensions
* @param middlewares A list of Express middlewares that handle other functions
*/
private async registerServices(routers: Array<AuracleApiRouter>, modules: Array<any>, middlewares: Array<any>) {
return Promise.all([
this.modules(modules),
this.routers(routers),
this.middlewares(middlewares)
])
.catch((err) => {
throw err
})
}
/** /**
* Initializes the App with a bunch of modules like helmet, cors, morgan... * Initializes the App with a bunch of modules like helmet, cors, morgan...
* @param modules An array of modules and extensions * @param modules An array of modules and extensions
*/ */
private modules = async (modules: Array<any>) => { private async modules(modules: Array<any>) {
try { try {
modules.forEach((module) => { modules.forEach(module => this.app.use(module))
this.app.use(module)
})
} catch (err) { } catch (err) {
console.error('Unable to initialize modules and extensions.') console.error(VSColors.red, '[ERROR] Unable to initialize modules and extensions.')
throw err throw err
} }
} }
@@ -81,26 +95,22 @@ export class AuracleApi {
* Initializes routers * Initializes routers
* @param routers An array of AuracleApiRouter children objects * @param routers An array of AuracleApiRouter children objects
*/ */
private routers = async (routers: Array<AuracleApiRouter>) => { private async routers(routers: Array<AuracleApiRouter>) {
try { try {
routers.forEach((router) => { routers.forEach(router => this.app.use(`${this.baseUrl}`, router.instance))
this.app.use(`${this.baseUrl}`, router.instance)
})
} catch (err) { } catch (err) {
console.error('Unable to initialize routers.') console.error(VSColors.red, '[ERROR] Unable to initialize routers.')
throw err throw err
} }
} }
private middlewares = async (middleWares: { private async middlewares(middleWares: {
forEach: (arg0: (middleWare: any) => void) => void; forEach: (arg0: (middleWare: any) => void) => void;
}) => { }) {
try { try {
middleWares.forEach((middleWare) => { middleWares.forEach(middleWare => this.app.use(middleWare))
this.app.use(middleWare)
})
} catch (err) { } catch (err) {
console.error('Unable to initialize middlewares.') console.error(VSColors.red, '[ERROR] Unable to initialize middlewares.')
throw err throw err
} }
} }
@@ -108,9 +118,7 @@ export class AuracleApi {
/** /**
* Allows the App to run on its given port * Allows the App to run on its given port
*/ */
public listen = () => { public listen() {
this.app.listen(this.port, () => { this.app.listen(this.port, () => console.info(VSColors.green, `App listening on port ${this.port} !`))
console.log(`App listening on port ${this.port}`)
})
} }
} }

View File

@@ -22,7 +22,7 @@ import { SpellRouter } from './routes/SpellRouter';
const apiPort = process.env.API_PORT const apiPort = process.env.API_PORT
const app = new AuracleApi({ const api = new AuracleApi({
port: apiPort, port: apiPort,
database: AuracleDatabaseDriver, database: AuracleDatabaseDriver,
@@ -36,6 +36,3 @@ const app = new AuracleApi({
helmet() helmet()
], ],
}) })
// Listens on apiPort...
app.listen()