1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00
unleash.unleash/lib/server-impl.js

104 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-06-18 21:53:18 +02:00
'use strict';
2016-10-26 10:43:11 +02:00
const { EventEmitter } = require('events');
const migrator = require('../migrator');
2016-11-13 21:09:00 +01:00
const getApp = require('./app');
const { startMonitoring } = require('./metrics');
const { createStores } = require('./db');
const { createOptions } = require('./options');
const StateService = require('./state-service');
const User = require('./user');
const permissions = require('./permissions');
const AuthenticationRequired = require('./authentication-required');
const { addEventHook } = require('./event-hook');
async function createApp(options) {
// Database dependencies (stateful)
const logger = options.getLogger('server-impl.js');
const eventBus = new EventEmitter();
const stores = createStores(options, eventBus);
const secret = await stores.settingStore.get('unleash.secret');
const config = {
stores,
eventBus,
secret,
logFactory: options.getLogger, // TODO: remove in v4.x
...options,
};
2016-11-13 15:15:52 +01:00
const app = getApp(config);
startMonitoring(config);
if (typeof config.eventHook === 'function') {
addEventHook(config.eventHook, stores.eventStore);
}
const stateService = new StateService(config);
config.stateService = stateService;
if (config.importFile) {
await stateService.importFile({
file: config.importFile,
dropBeforeImport: config.dropBeforeImport,
userName: 'import',
});
}
return new Promise((resolve, reject) => {
2020-06-17 08:03:02 +02:00
const payload = {
app,
config,
stores,
eventBus,
stateService,
};
if (options.start) {
const server = app.listen(options.listen, () =>
logger.info('Unleash has started.', server.address()),
);
2020-07-13 21:40:22 +02:00
server.keepAliveTimeout = options.keepAliveTimeout;
server.headersTimeout = options.headersTimeout;
2020-06-17 08:03:02 +02:00
server.on('listening', () => {
resolve({ ...payload, server });
});
server.on('error', reject);
} else {
resolve({ ...payload });
}
});
}
async function start(opts) {
const options = createOptions(opts);
const logger = options.getLogger('server-impl.js');
try {
if (options.disableDBMigration) {
logger.info('DB migrations disabled');
} else {
await migrator(options);
}
} catch (err) {
logger.error('Failed to migrate db', err);
throw err;
}
2020-05-02 09:12:36 +02:00
return createApp(options);
}
2020-06-17 08:03:02 +02:00
async function create(opts) {
return start({ ...opts, start: false });
}
module.exports = {
2016-06-18 21:55:46 +02:00
start,
2020-06-17 08:03:02 +02:00
create,
User,
AuthenticationRequired,
permissions,
};