sakuraapi / cli

Command Line Interface for Scaffolding and Managing SakuraAPI Projects
BSD 3-Clause "New" or "Revised" License
4 stars 1 forks source link

Move process.on `unhandledRejection` and `uncaughtException` into Server.start so Log service can be used #11

Closed etsuo closed 6 years ago

etsuo commented 6 years ago

Right now, this is setup outside of the Server class in src/index.ts - it'd be better to have it in the start method, so it has access to log service.

I believe that since Boostrap().boot() is called within a try/catch block, it will catch anything that bubbles out of boot.

etsuo commented 6 years ago

Negative ghost-ride. Turns out this won't work if something barfs during the bootstrap. Rethink this.

etsuo commented 6 years ago

Perhaps something like this:

import {SakuraApi}  from '@sakuraapi/api';
import 'colors';
import * as fs      from 'fs';
import * as util    from 'util';
import './api';
import {Bootstrap}  from './sakura-api';
import {LogService} from './services/log';

// tslint:disable:no-console
/**
 * See `./sakuraapi.ts` for configuration of SakuraApi.
 */
class Server {
  sapi: SakuraApi;
  log: LogService;

  async start() {

    process.on('unhandledRejection', (err) => {
      (this.log)
        ? this.log.error('unhandledRejection', err)
        : console.log('unhandledRejection', err);
    });

    process.on('uncaughtException', (err) => {
      (this.log)
      ? this.log.error('uncaughtException', err)
      : console.log('uncaughtException', err);
    });

    try {
      this.sapi = await new Bootstrap().boot();
      this.log = this.sapi.getProvider(LogService);

      await this
        .sapi
        .listen({
          bootMessage: `SAPI :: port: ${this.sapi.port} :: By your command |<\n`.green
        });

      this.log.info(`SAPI :: port: ${this.sapi.port} started`);

      const writeFile = util.promisify(fs.writeFile);

      const configJson = JSON.stringify(this.sapi.config, null, 2);
      await writeFile('config.json', configJson, 'utf8');

    } catch (err) {
      if (!this.sapi) {
        throw err;
      } else {
        this.log.error('Error starting Profile Server', err);
      }
    }
  }
}

new Server().start();

// tslint:enable:no-console