app.js 1.63 KB
/**
 * app.js
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2017/04/13
 */
'use strict';

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const Express = require('express');
const mongoose = require('mongoose');
const pkg = require('./package.json');

const path = require('path');

global.env = {
    version: pkg.version,
    Production: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'gray',
    Gray: process.env.NODE_ENV === 'gray',
    Test: (process.env.NODE_ENV || '').indexOf('test') >= 0
};

let app = new Express();

const config = require('./server/common/config');
const logger = require('yoho-node-lib/lib/logger').init(config);
const helpers = require('yoho-node-lib/lib/helpers');

global.yoho = {
    logger,
    helpers,
    config
};

app.use(compression());
app.use(Express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.json({
    limit: 1 * 1024 * 1024 // 限制请求长度1m
}));
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

const middleware = require('./server/middleware');
const controllers = require('./server/controllers');

require('./server/db'); // register db
mongoose.connect(config.mongodb.url, {
    useMongoClient: true,
});
mongoose.Promise = global.Promise;

try {
    app.use((req, res, next) => {
        next();
    });

    // controller
    app.use('/api', controllers);

    // 异常捕获中间件
    app.use(middleware.error);
} catch (err) {
    logger.error(err);
}


app.listen(config.port, () => {
    logger.info(`yoho mongo search start at ${config.port}`);
});