2016-06-18 21:53:18 +02:00
|
|
|
'use strict';
|
2016-10-26 10:43:11 +02:00
|
|
|
|
2016-10-27 20:51:21 +02:00
|
|
|
const eventType = require('../event-type');
|
2016-06-20 10:27:19 +02:00
|
|
|
const logger = require('../logger');
|
2016-10-27 20:51:21 +02:00
|
|
|
const NotFoundError = require('../error/notfound-error');
|
2016-06-18 21:53:18 +02:00
|
|
|
const STRATEGY_COLUMNS = ['name', 'description', 'parameters_template'];
|
2016-11-05 10:16:48 +01:00
|
|
|
const TABLE = 'strategies';
|
2014-11-17 22:39:04 +01:00
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
class StrategyStore {
|
|
|
|
constructor (db, eventStore) {
|
|
|
|
this.db = db;
|
|
|
|
eventStore.on(eventType.strategyCreated, event => this._createStrategy(event.data));
|
|
|
|
eventStore.on(eventType.strategyDeleted, event => {
|
|
|
|
db(TABLE)
|
|
|
|
.where('name', event.data.name)
|
|
|
|
.del()
|
|
|
|
.catch(err => {
|
|
|
|
logger.error('Could not delete strategy, error was: ', err);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2014-12-08 20:56:22 +01:00
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
getStrategies () {
|
|
|
|
return this.db
|
2016-05-01 22:53:09 +02:00
|
|
|
.select(STRATEGY_COLUMNS)
|
2016-11-05 10:16:48 +01:00
|
|
|
.from(TABLE)
|
2016-05-01 22:53:09 +02:00
|
|
|
.orderBy('created_at', 'asc')
|
2016-11-05 10:16:48 +01:00
|
|
|
.map(this.rowToStrategy);
|
2016-05-01 22:53:09 +02:00
|
|
|
}
|
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
getStrategy (name) {
|
|
|
|
return this.db
|
2016-05-01 22:53:09 +02:00
|
|
|
.first(STRATEGY_COLUMNS)
|
2016-11-05 10:16:48 +01:00
|
|
|
.from(TABLE)
|
2016-06-18 21:53:18 +02:00
|
|
|
.where({ name })
|
2016-11-05 10:16:48 +01:00
|
|
|
.then(this.rowToStrategy);
|
2016-05-01 22:53:09 +02:00
|
|
|
}
|
2014-11-17 22:39:04 +01:00
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
rowToStrategy (row) {
|
2016-05-01 22:53:09 +02:00
|
|
|
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,
|
2016-06-18 21:55:46 +02:00
|
|
|
parametersTemplate: row.parameters_template,
|
2016-05-01 22:53:09 +02:00
|
|
|
};
|
2014-11-17 22:39:04 +01:00
|
|
|
}
|
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
eventDataToRow (data) {
|
2016-05-01 22:53:09 +02:00
|
|
|
return {
|
|
|
|
name: data.name,
|
|
|
|
description: data.description,
|
|
|
|
parameters_template: data.parametersTemplate // eslint-disable-line
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
_createStrategy (data) {
|
|
|
|
this.db(TABLE)
|
|
|
|
.insert(this.eventDataToRow(data))
|
2016-12-02 16:20:13 +01:00
|
|
|
.catch(err => logger.error('Could not insert strategy, error was: ', err));
|
2016-05-01 22:53:09 +02:00
|
|
|
}
|
2014-11-17 22:39:04 +01:00
|
|
|
};
|
|
|
|
|
2016-11-05 10:16:48 +01:00
|
|
|
module.exports = StrategyStore;
|
|
|
|
|