From ed9d095e78e718ab9c3dc6391a5790c6256f7d3e Mon Sep 17 00:00:00 2001 From: Matthew R Date: Sat, 16 Nov 2019 19:24:24 -0500 Subject: [PATCH] Add express server class --- src/api/Server.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/api/index.ts | 2 ++ 2 files changed, 48 insertions(+) create mode 100644 src/api/Server.ts create mode 100644 src/api/index.ts diff --git a/src/api/Server.ts b/src/api/Server.ts new file mode 100644 index 0000000..18496b1 --- /dev/null +++ b/src/api/Server.ts @@ -0,0 +1,46 @@ +/* eslint-disable no-useless-return */ +import express from 'express'; +import bodyParser from 'body-parser'; +import fs from 'fs-extra'; +import { Client } from '..'; +import { Security } from '.'; +import { Route } from '../class'; + +export default class Server { + public routes: Map; + + public client: Client; + + public security: Security; + + public app: express.Express; + + public options: { port: number } + + constructor(client: Client, options?: { port: number }) { + this.options = options; + this.routes = new Map(); + this.client = client; + this.security = new Security(this.client); + this.app = express(); + this.connect(); + this.loadRoutes(); + } + + private async loadRoutes(): Promise { + const routes = await fs.readdir('./routes'); + routes.forEach(async (routeFile) => { + if (routeFile === 'index.js') return; + const route: Route = new (require(`./${routeFile}`))(this); + this.routes.set(route.conf.path, route); + this.app.use(route.conf.path, route.router); + }); + } + + private connect(): void { + this.app.use(bodyParser.json()); + this.app.listen(this.options.port, () => { + this.client.signale.success(`API Server listening on port ${this.options.port}`); + }); + } +} diff --git a/src/api/index.ts b/src/api/index.ts new file mode 100644 index 0000000..4e70cd1 --- /dev/null +++ b/src/api/index.ts @@ -0,0 +1,2 @@ +export { default as Server } from './Server'; +export { default as Security } from './Security';