Ghost/core/server/api/roles.js
kirrg001 1e2beface1 Refactored the API layer: do not handle API response after pipelining
no issue

- this has a big underlying problem
- each task in the pipeline can modify the options
- e.g. add a proper permission context
- if we chain after the pipeline, we don't have access to the modified options object
- and then we pass the wrong options into the `toJSON` function of a model
- the toJSON function decides what to return based on options
- this is the easiest solution for now, but i am going to write a spec if we can solve this problem differently
2017-09-28 10:18:18 +01:00

79 lines
2.4 KiB
JavaScript

// # Roles API
// RESTful API for the Role resource
var Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
canThis = require('../permissions').canThis,
models = require('../models'),
docName = 'roles',
roles;
/**
* ## Roles API Methods
*
* **See:** [API Methods](index.js.html#api%20methods)
*/
roles = {
/**
* ### Browse
* Find all roles
*
* If a 'permissions' property is passed in the options object then
* the results will be filtered based on whether or not the context user has the given
* permission on a role.
*
*
* @public
* @param {{context, permissions}} options (optional)
* @returns {Promise(Roles)} Roles Collection
*/
browse: function browse(options) {
var permittedOptions = ['permissions'],
tasks;
/**
* ### Model Query
* Make the call to the Model layer
* @param {Object} options
* @returns {Object} options
*/
function modelQuery(options) {
return models.Role.findAll(options)
.then(function onModelResponse(models) {
var roles = models.map(function (role) {
return role.toJSON();
});
if (options.permissions !== 'assign') {
return {roles: roles};
}
return Promise.filter(roles.map(function (role) {
return canThis(options.context).assign.role(role)
.return(role)
.catch(function () {});
}), function (value) {
return value && value.name !== 'Owner';
}).then(function (roles) {
return {
roles: roles
};
});
});
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
apiUtils.validate(docName, {opts: permittedOptions}),
apiUtils.handlePermissions(docName, 'browse'),
modelQuery
];
// Pipeline calls each task passing the result of one to be the arguments for the next
return pipeline(tasks, options);
}
};
module.exports = roles;