有没有办法引导Express应用程序?

时间:2016-07-27 12:40:32

标签: express bootstrapping

我正在Express中构建一个应用程序,但我希望在服务器实际启动之前调用S3来检索一些密钥。 Express中有可能吗?如果我谷歌bootstrap Express我会点击设置Express与twitter Bootstrap。

之前我使用过Sails.js,你可以在bootstrap.js文件中指定bootstrap配置,所以我想我正在寻找类似的东西。否则有其他选择吗?

我有一个index.js文件和一个单独的bin / www文件,它调用index.js文件。我想在index.js中完成bootstrapping,以便它作为测试的一部分包含在内。现在我'初始化'引导程序,但由于它是异步的,服务器已经启动并运行在引导程序完成(或出错)之前,即

import express from 'express';
import {initializeFromS3} from './services/initializerService';
import healthCheckRouter from './routes/healthCheckRouter';
import bodyParser from 'body-parser';

initializeFromS3(); // Calls out to S3 and does some bootstrapping of configurations
const app = express();

app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

// ---------------------------- Routes ----------------------------
app.use('/', express.static('dist/client/'));
app.use('/health-check', healthCheckRouter);

export default app;

1 个答案:

答案 0 :(得分:0)

为遇到相同问题并且头脑空白的任何人发布我的解决方案。我分别保留了bin / www和index.js文件,但是通过方法从index.js返回了express对象。感谢友好的Github人员。

Index.js文件:

import express from 'express';
import {initialize} from './services/appService';
import healthCheckRouter from './routes/healthCheckRouter';
import loginRouter from './routes/loginRouter';


export function getExpress() {
  return initialize()
    .then(() => {
      const app = express();

      // ---------------------------- Routes ----------------------------
      app.use('/', express.static('dist/client/'));
      app.use('/login', loginRouter);
      app.use('/health-check', healthCheckRouter);
      return app;
    })
}

bin / www文件:

import winston from 'winston';
import bodyParser from 'body-parser';

import {getExpress} from '../index';

getExpress()
  .then(app => {
    app.use(bodyParser.json());       // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
      extended: true
    }));

    const port = 3002;
    app.listen(port, () => {
      winston.info(`Server listening on port ${port}!`);
    });
  })
  .catch(err => {
    winston.error('Error starting server', err);
  });

集成测试:

import request from 'supertest';
import {getExpress} from '../../index'

describe('/login integration test', () => {
  let app = null;

  beforeEach(done => {
    getExpress()
      .then(res => {
        app = res;
        done();
      });
  });

  describe('GET /login', () => {
    it('should return 400 error if \'app\' is not provided as a query string', done => {
      request(app)
        .get('/login')
        .expect(400, done);
    });
  });
});