Controller classes to implement HTTP methods
It would be nice to have actual controller instances based from Controller classes to define HTTP route endpoint handlers:
class CatalogListController {
constructor(spec) {
this.bus = spec.bus;
this.type = spec.type;
}
get(req, res, next) {
const args = {
channel: req.identity.channel,
type: this.type,
platform: req.identity.platform,
user: req.identity.user,
include: req.query.include.split(','),
limit: req.query.limit
};
this.bus
.query({role: 'catalog', cmd: 'fetchItemList'}, args)
.then(resources => {
res.status(200);
res.body = resources;
next();
})
.catch(next);
}
post(req, res, next) {
const payload = _.cloneDeep(req.body);
payload.channel = req.identity.channel.id;
payload.type = this.type;
this.bus
.sendCommand({role: 'catalog', cmd: 'setItem'}, payload)
.then(resource => {
res.body = resource;
res.status(201);
next();
})
.catch(next);
}
static create(spec) {
if (!spec.bus || !_.isObject(spec.bus)) {
throw new Error('CatalogListController spec.bus is required');
}
if (!spec.type || !_.isString(spec.type)) {
throw new Error('CatalogListController spec.type is required');
}
return controller.create(new CatalogListController(spec));
}
}
module.exports = CatalogListController;
This way, users of the Oddworks library can subclass and override the controllers to extend the core with application specific functionality. Additionally the controllers could be used to cause the HTTP API to return the proper Method Not Allowed response if the method is not supported in the controller:
router.all(
`/${type}s/:id`,
bus.query({middleware: 'authorize'}, {bus, audience: {
get: ['admin', 'platform'],
patch: ['admin'],
delete: ['admin']
}}),
CatalogItemController.create({bus, type})
);