DavideViolante/Angular-Full-Stack

Organizing the `app.js` to be more Typescript like and adding flexibility to use other libs like Socket.io, ngUniversal and etc.

marioteik opened this issue · 0 comments

It's needed to extend if you need to use SSR, let the core be more clear and give more flexibility to implement other libs like Socket.io.

The proposal is to rewrite the app.js to be more like this:

import * as express from 'express';
import * as morgan from 'morgan';
import * as mongoose from 'mongoose';
import { json, urlencoded } from 'body-parser';
import { load } from 'dotenv';
import { join } from 'path';
import { createServer, Server } from 'http';

import setRoutes from './routes';

export class AppServer {
    public static readonly PORT: number = 8080;
    public static readonly DIST_FOLDER: string = join(process.cwd(), 'dist');
    public static readonly PUBLIC_FOLDER: string = join(process.cwd(), 'public');

    private app: express.Application;
    private server: Server;
    private mongodb;
    private port: string | number;
    private mongodbURI: string;

    constructor() {
        // get .env file for enviromniment
        load({ path: '.env' });

        this.createApp();
        this.config();
        this.configMongoDB();
        this.createServer();
        this.listen();
    }

    private createApp(): void {
        this.app = express();
    }

    private createServer(): void {
        this.server = createServer(this.app);
    }

    private config(): void {
        this.port = process.env.PORT_SERVER || AppServer.PORT;

        this.app.use('/', express.static(AppServer.PUBLIC_FOLDER));
        this.app.use(json());
        this.app.use(urlencoded({ extended: false }));
    }

    private configMongoDB() {
        if (process.env.NODE_ENV === 'test') {
            this.mongodbURI = process.env.MONGODB_TEST_URI;
        } else {
            this.mongodbURI = process.env.MONGODB_URI;
            this.app.use(morgan('dev'));
        }

        mongoose.Promise = global.Promise;
        this.mongodb = mongoose.connect(this.mongodbURI);
    }

    private listen(): void {
        this.mongodb
            .then(db => {
                console.log('Connected to MongoDB');

                setRoutes(this.app);

                this.app.get('/', (req, res) => {
                    res.render(
                        join(AppServer.DIST_FOLDER, 'public', 'index.html'),
                        { req }
                    );
                });

                this.server.listen(this.port, () => {
                    console.log(
                        'APP listening on port ' + this.port
                    );
                });
            })
            .catch(err => {
                console.error(err);
            });
    }

    public getApp(): express.Application {
        return this.app;
    }
}

const app = new AppServer().getApp();

export { app };