diff --git a/lib/strategyApi.js b/lib/strategyApi.js index 0cf580be20..19413f1236 100644 --- a/lib/strategyApi.js +++ b/lib/strategyApi.js @@ -1,3 +1,5 @@ +var strategyDb = require('./strategyDb'); + var strategies = [ { name: "default", @@ -21,7 +23,9 @@ function byName(name) { module.exports = function (app) { app.get('/strategies', function (req, res) { - res.json({strategies: strategies}); + strategyDb.getStrategies().then(function (strategies) { + res.json({strategies: strategies}); + }); }); app.get('/strategies/:name', function (req, res) { diff --git a/lib/strategyDb.js b/lib/strategyDb.js new file mode 100644 index 0000000000..c76b881360 --- /dev/null +++ b/lib/strategyDb.js @@ -0,0 +1,56 @@ +var eventStore = require('./eventStore'); +var eventType = require('./eventType'); +var logger = require('./logger'); +var knex = require('./dbPool'); +var STRATEGY_COLUMNS = ['name', 'description', 'parameters_template']; + +eventStore.on(eventType.strategyCreated, function (event) { + knex('strategies') + .insert(eventToRow(event)) + .catch(function (err) { + logger.error('Could not insert strategy, error was: ', err); + }); +}); + +function getStrategies() { + return knex + .select(STRATEGY_COLUMNS) + .from('strategies') + .orderBy('created_at', 'desc') + .map(rowToStrategy); +} + +function getStrategy(name) { + return knex + .first(STRATEGY_COLUMNS) + .from('strategies') + .where({name: name}) + .then(rowToStrategy); +} + +function rowToStrategy(row) { + if (!row) { + throw new Error('invalid row'); + } + + return { + name: row.name, + description: row.description, + enabled: row.enabled > 0, + parametersTemplate: row.parameters_template // jshint ignore: line + }; +} + +function eventToRow(event) { + return { + name: event.data.name, + description: event.data.description, + parameters_template: event.data.parametersTemplate // jshint ignore: line + }; +} + +module.exports = { + getStrategies: getStrategies, + getStrategy: getStrategy +}; +