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