fix: wait for config file validation

This commit is contained in:
Anselm Stordeur
2019-01-14 16:45:07 +01:00
committed by Rainer Killinger
parent 90822f5888
commit 30082f8726

View File

@@ -36,8 +36,9 @@ import {Elasticsearch} from './storage/elasticsearch/Elasticsearch';
export const app = express(); export const app = express();
// only accept json as content type for all requests async function configureApp() {
app.use(bodyParser.json({ // only accept json as content type for all requests
app.use(bodyParser.json({
limit: '500kb', limit: '500kb',
type: (req) => { type: (req) => {
const contentType = typeof req.headers['Content-Type'] === 'string' ? const contentType = typeof req.headers['Content-Type'] === 'string' ?
@@ -48,69 +49,69 @@ app.use(bodyParser.json({
throw new SCUnsupportedMediaTypeErrorResponse(process.env.NODE_ENV !== 'production'); throw new SCUnsupportedMediaTypeErrorResponse(process.env.NODE_ENV !== 'production');
} }
}, },
})); // 500kb should be reasonably large })); // 500kb should be reasonably large
// use morgan as a request logger // use morgan as a request logger
// request loggers have to be the first middleware to be set in express // request loggers have to be the first middleware to be set in express
app.use(morgan('dev')); app.use(morgan('dev'));
const databases: {[name: string]: DatabaseConstructor} = { const databases: {[name: string]: DatabaseConstructor} = {
elasticsearch: Elasticsearch, elasticsearch: Elasticsearch,
}; };
// validate config file // validate config file
export const scValidator = new Validator(); const scValidator = new Validator();
scValidator.addSchemas(join('node_modules', '@openstapps', 'core', 'lib', 'schema')); await scValidator.addSchemas(join('node_modules', '@openstapps', 'core', 'lib', 'schema'));
// validate the config file // validate the config file
const configValidation = scValidator.validate(config.util.toObject(), 'SCConfigFile'); const configValidation = scValidator.validate(config.util.toObject(), 'SCConfigFile');
// validation failed // validation failed
if (configValidation.errors.length > 0) { if (configValidation.errors.length > 0) {
throw new Error( throw new Error(
'Validation of config file failed. Errors were: ' + 'Validation of config file failed. Errors were: ' +
JSON.stringify(configValidation.errors), JSON.stringify(configValidation.errors),
); );
} }
// check if a database name was given // check if a database name was given
if (!config.has('internal.database.name')) { if (!config.has('internal.database.name')) {
throw new Error('You have to configure a database'); throw new Error('You have to configure a database');
} }
if (typeof mailer !== 'undefined') { if (typeof mailer !== 'undefined') {
// set a mailQueue to use the backend mailer // set a mailQueue to use the backend mailer
if (config.has('internal.monitoring')) { if (config.has('internal.monitoring')) {
app.set('mailQueue', new MailQueue(mailer)); app.set('mailQueue', new MailQueue(mailer));
} }
} }
const database = const database =
new databases[config.get<string>('internal.database.name')]( new databases[config.get<string>('internal.database.name')](
config.util.toObject(), config.util.toObject(),
app.get('mailQueue'), app.get('mailQueue'),
); );
if (typeof database === 'undefined') { if (typeof database === 'undefined') {
throw new Error('No implementation for configured database found. Please check your configuration.'); throw new Error('No implementation for configured database found. Please check your configuration.');
} }
logger.ok('Validated config file sucessfully'); logger.ok('Validated config file sucessfully');
// make the validator available on the app // make the validator available on the app
app.set('validator', scValidator); app.set('validator', scValidator);
// treats /foo and /foo/ as two different routes // treats /foo and /foo/ as two different routes
// see http://expressjs.com/en/api.html#app.set // see http://expressjs.com/en/api.html#app.set
app.set('strict routing', true); app.set('strict routing', true);
// make the bulk storage available to all http middlewares/routes // make the bulk storage available to all http middlewares/routes
app.set( app.set(
'bulk', 'bulk',
new BulkStorage(database), new BulkStorage(database),
); );
const corsOptions = { const corsOptions = {
allowedHeaders: [ allowedHeaders: [
'DNT', 'DNT',
'Keep-Alive', 'Keep-Alive',
@@ -125,20 +126,20 @@ const corsOptions = {
maxAge: 1728000, maxAge: 1728000,
methods: ['GET', 'POST', 'PUT', 'OPTIONS'], methods: ['GET', 'POST', 'PUT', 'OPTIONS'],
optionsSuccessStatus: 204, optionsSuccessStatus: 204,
}; };
// allow all origins on all routes // allow all origins on all routes
app.use(cors(corsOptions)); app.use(cors(corsOptions));
// TODO: See if it can handle options request with no content-type // TODO: See if it can handle options request with no content-type
// allow cors preflight requests on every route // allow cors preflight requests on every route
app.options('*', cors(corsOptions)); app.options('*', cors(corsOptions));
app.set('isProductiveEnvironment', process.env.NODE_ENV !== 'production'); app.set('isProductiveEnvironment', process.env.NODE_ENV !== 'production');
// load routes before plugins // load routes before plugins
// they now can be used or overwritten by any plugin // they now can be used or overwritten by any plugin
app.use( app.use(
bulkAddRouter, bulkAddRouter,
bulkDoneRouter, bulkDoneRouter,
bulkRouter, bulkRouter,
@@ -146,13 +147,20 @@ app.use(
multiSearchRouter, multiSearchRouter,
searchRouter, searchRouter,
thingUpdateRouter, thingUpdateRouter,
); );
// add a route for a missing resource (404) // add a route for a missing resource (404)
app.use((_req, res) => { app.use((_req, res) => {
const errorResponse = new SCNotFoundErrorResponse(process.env.NODE_ENV !== 'production'); const errorResponse = new SCNotFoundErrorResponse(process.env.NODE_ENV !== 'production');
res.status(errorResponse.statusCode); res.status(errorResponse.statusCode);
res.json(errorResponse); res.json(errorResponse);
}); });
// TODO: implement a route to register plugins // TODO: implement a route to register plugins
}
configureApp().then(() => {
logger.ok('Sucessfully configured express server');
}).catch((err) => {
throw err;
});