1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-04 00:18:01 +01:00

chore(modernize): Admin StrategyController

This commit is contained in:
ivaosthu 2018-12-05 21:07:45 +01:00 committed by Ivar Conradi Østhus
parent a6d61f421b
commit 8b734d1ef5
2 changed files with 113 additions and 122 deletions

View File

@ -4,7 +4,7 @@ const Controller = require('../controller');
const FeatureController = require('./feature.js'); const FeatureController = require('./feature.js');
const ArchiveController = require('./archive.js'); const ArchiveController = require('./archive.js');
const EventController = require('./event.js'); const EventController = require('./event.js');
const strategies = require('./strategy'); const StrategyController = require('./strategy');
const MetricsController = require('./metrics'); const MetricsController = require('./metrics');
const UserController = require('./user'); const UserController = require('./user');
const apiDef = require('./api-def.json'); const apiDef = require('./api-def.json');
@ -18,7 +18,7 @@ class AdminApi extends Controller {
this.app.get('/', this.index); this.app.get('/', this.index);
this.app.use('/features', new FeatureController(stores).router); this.app.use('/features', new FeatureController(stores).router);
this.app.use('/archive', new ArchiveController(stores).router); this.app.use('/archive', new ArchiveController(stores).router);
this.app.use('/strategies', strategies.router(config)); this.app.use('/strategies', new StrategyController(stores).router);
this.app.use('/events', new EventController(stores).router); this.app.use('/events', new EventController(stores).router);
this.app.use('/metrics', new MetricsController(stores).router); this.app.use('/metrics', new MetricsController(stores).router);
this.app.use('/user', new UserController().router); this.app.use('/user', new UserController().router);

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const { Router } = require('express'); const Controller = require('../controller');
const joi = require('joi'); const joi = require('joi');
const eventType = require('../../event-type'); const eventType = require('../../event-type');
@ -10,139 +10,130 @@ const extractUser = require('../../extract-user');
const strategySchema = require('./strategy-schema'); const strategySchema = require('./strategy-schema');
const version = 1; const version = 1;
const handleError = (req, res, error) => { class StrategyController extends Controller {
logger.warn('Error creating or updating strategy', error); constructor({ strategyStore, eventStore }) {
switch (error.name) { super();
case 'NotFoundError': this.strategyStore = strategyStore;
return res.status(404).end(); this.eventStore = eventStore;
case 'NameExistsError':
return res this.get('/', this.getAllStratgies);
.status(403) this.get('/:name', this.getStrategy);
.json([ this.delete('/:name', this.removeStrategy);
{ this.post('/', this.createStrategy);
msg: `A strategy named '${ this.put('/:strategyName', this.updateStrategy);
req.body.name
}' already exists.`,
},
])
.end();
case 'ValidationError':
return res
.status(400)
.json(error)
.end();
default:
logger.error('Could perfom operation', error);
return res.status(500).end();
} }
};
function validateEditable(strategyName) { async getAllStratgies(req, res) {
return strategy => { const strategies = await this.strategyStore.getStrategies();
if (strategy.editable === false) { res.json({ version, strategies });
throw new Error( }
`Cannot edit strategy ${strategyName}, editable is false`
); async getStrategy(req, res) {
try {
const name = req.params.name;
const strategy = await this.strategyStore.getStrategy(name);
res.json(strategy).end();
} catch (err) {
res.status(404).json({ error: 'Could not find strategy' });
} }
return strategy; }
};
}
function validateInput(data) { async removeStrategy(req, res) {
return new Promise((resolve, reject) => {
joi.validate(data, strategySchema, (err, cleaned) => {
if (err) {
return reject(err);
}
return resolve(cleaned);
});
});
}
exports.router = function(config) {
const { strategyStore, eventStore } = config.stores;
const router = Router();
router.get('/', (req, res) => {
strategyStore.getStrategies().then(strategies => {
res.json({ version, strategies });
});
});
router.get('/:name', (req, res) => {
strategyStore
.getStrategy(req.params.name)
.then(strategy => res.json(strategy).end())
.catch(() =>
res.status(404).json({ error: 'Could not find strategy' })
);
});
router.delete('/:name', (req, res) => {
const strategyName = req.params.name; const strategyName = req.params.name;
strategyStore try {
.getStrategy(strategyName) const strategy = await this.strategyStore.getStrategy(strategyName);
.then(validateEditable(strategyName)) await this._validateEditable(strategy);
.then(() => await this.eventStore.store({
eventStore.store({ type: eventType.STRATEGY_DELETED,
type: eventType.STRATEGY_DELETED, createdBy: extractUser(req),
createdBy: extractUser(req), data: {
data: { name: strategyName,
name: strategyName, },
}, });
}) res.status(200).end();
) } catch (error) {
.then(() => res.status(200).end()) this._handleErrorResponse(req, res, error);
.catch(error => handleError(req, res, error)); }
}); }
function validateStrategyName(data) { async createStrategy(req, res) {
try {
const newStrategy = await joi.validate(req.body, strategySchema);
await this._validateStrategyName(newStrategy);
await this.eventStore.store({
type: eventType.STRATEGY_CREATED,
createdBy: extractUser(req),
data: newStrategy,
});
res.status(201).end();
} catch (error) {
this._handleErrorResponse(req, res, error);
}
}
async updateStrategy(req, res) {
const input = req.body;
try {
const updatedStrategy = await joi.validate(input, strategySchema);
const strategy = await this.strategyStore.getStrategy(input.name);
await this._validateEditable(strategy);
await this.eventStore.store({
type: eventType.STRATEGY_UPDATED,
createdBy: extractUser(req),
data: updatedStrategy,
});
res.status(200).end();
} catch (error) {
this._handleErrorResponse(req, res, error);
}
}
// This check belongs in the store.
async _validateStrategyName(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
strategyStore this.strategyStore
.getStrategy(data.name) .getStrategy(data.name)
.then(() => .then(() =>
reject(new NameExistsError('Strategy already exist!')) reject(
new NameExistsError(
`Strategy with name ${data.name} already exist!`
)
)
) )
.catch(() => resolve(data)); .catch(() => resolve(data));
}); });
} }
router.post('/', (req, res) => { // This check belongs in the store.
const data = req.body; _validateEditable(strategy) {
validateInput(data) if (strategy.editable === false) {
.then(validateStrategyName) throw new Error(`Cannot edit strategy ${strategy.name}`);
.then(newStrategy => }
eventStore.store({ }
type: eventType.STRATEGY_CREATED,
createdBy: extractUser(req),
data: newStrategy,
})
)
.then(() => res.status(201).end())
.catch(error => handleError(req, res, error));
});
router.put('/:strategyName', (req, res) => { _handleErrorResponse(req, res, error) {
const strategyName = req.params.strategyName; logger.warn('Error creating or updating strategy', error);
const updatedStrategy = req.body; switch (error.name) {
case 'NotFoundError':
return res.status(404).end();
case 'NameExistsError':
return res
.status(403)
.json([{ msg: error.message }])
.end();
case 'ValidationError':
return res
.status(400)
.json(error)
.end();
default:
logger.error('Could perfom operation', error);
return res.status(500).end();
}
}
}
updatedStrategy.name = strategyName; module.exports = StrategyController;
strategyStore
.getStrategy(strategyName)
.then(validateEditable(strategyName))
.then(() => validateInput(updatedStrategy))
.then(() =>
eventStore.store({
type: eventType.STRATEGY_UPDATED,
createdBy: extractUser(req),
data: updatedStrategy,
})
)
.then(() => res.status(200).end())
.catch(error => handleError(req, res, error));
});
return router;
};