2014-11-17 22:39:04 +01:00
|
|
|
var eventStore = require('./eventStore');
|
|
|
|
var eventType = require('./eventType');
|
|
|
|
var logger = require('./logger');
|
|
|
|
var knex = require('./dbPool');
|
2015-02-12 11:41:30 +01:00
|
|
|
var NotFoundError = require('./error/NotFoundError');
|
2014-11-17 22:39:04 +01:00
|
|
|
var STRATEGY_COLUMNS = ['name', 'description', 'parameters_template'];
|
|
|
|
|
|
|
|
eventStore.on(eventType.strategyCreated, function (event) {
|
2014-12-09 14:44:25 +01:00
|
|
|
return createStrategy(event.data);
|
2014-11-17 22:39:04 +01:00
|
|
|
});
|
|
|
|
|
2014-12-08 20:56:22 +01:00
|
|
|
eventStore.on(eventType.strategyDeleted, function (event) {
|
|
|
|
knex('strategies')
|
|
|
|
.where('name', event.data.name)
|
|
|
|
.del()
|
|
|
|
.catch(function (err) {
|
|
|
|
logger.error('Could not delete strategy, error was: ', err);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2014-11-17 22:39:04 +01:00
|
|
|
function getStrategies() {
|
|
|
|
return knex
|
|
|
|
.select(STRATEGY_COLUMNS)
|
|
|
|
.from('strategies')
|
2014-11-29 11:51:57 +01:00
|
|
|
.orderBy('created_at', 'asc')
|
2014-11-17 22:39:04 +01:00
|
|
|
.map(rowToStrategy);
|
|
|
|
}
|
|
|
|
|
|
|
|
function getStrategy(name) {
|
|
|
|
return knex
|
|
|
|
.first(STRATEGY_COLUMNS)
|
|
|
|
.from('strategies')
|
2016-04-24 22:41:37 +02:00
|
|
|
.where({ name: name })
|
2014-11-17 22:39:04 +01:00
|
|
|
.then(rowToStrategy);
|
|
|
|
}
|
|
|
|
|
|
|
|
function rowToStrategy(row) {
|
|
|
|
if (!row) {
|
2015-02-12 11:41:30 +01:00
|
|
|
throw new NotFoundError('No strategy found');
|
2014-11-17 22:39:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
name: row.name,
|
|
|
|
description: row.description,
|
2016-04-24 22:41:37 +02:00
|
|
|
parametersTemplate: row.parameters_template
|
2014-11-17 22:39:04 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-12-09 14:44:25 +01:00
|
|
|
function eventDataToRow(data) {
|
2014-11-17 22:39:04 +01:00
|
|
|
return {
|
2014-12-09 14:44:25 +01:00
|
|
|
name: data.name,
|
|
|
|
description: data.description,
|
2016-04-24 22:41:37 +02:00
|
|
|
parameters_template: data.parametersTemplate // eslint-disable-line
|
2014-11-17 22:39:04 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-12-09 14:44:25 +01:00
|
|
|
function createStrategy(data) {
|
|
|
|
knex('strategies')
|
|
|
|
.insert(eventDataToRow(data))
|
|
|
|
.catch(function (err) {
|
|
|
|
logger.error('Could not insert strategy, error was: ', err);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-11-17 22:39:04 +01:00
|
|
|
module.exports = {
|
|
|
|
getStrategies: getStrategies,
|
2014-12-09 14:44:25 +01:00
|
|
|
getStrategy: getStrategy,
|
|
|
|
_createStrategy: createStrategy // visible for testing
|
2014-11-17 22:39:04 +01:00
|
|
|
};
|
|
|
|
|