Cleanup strapi-utils

This commit is contained in:
Alexandre Bodin 2019-12-11 10:22:47 +01:00
parent 3446b7f577
commit a503c20353
13 changed files with 110 additions and 252 deletions

View File

@ -519,14 +519,11 @@ const formatModelConnectionsGQL = function(
}); });
const policiesFn = [ const policiesFn = [
policyUtils.globalPolicy( policyUtils.globalPolicy({
undefined, controller: name,
{ action: 'find',
handler: `${name}.find`, plugin,
}, }),
undefined,
plugin
),
]; ];
policyUtils.get( policyUtils.get(

View File

@ -73,14 +73,11 @@ module.exports = {
// Push global policy to make sure the permissions will work as expected. // Push global policy to make sure the permissions will work as expected.
policiesFn.push( policiesFn.push(
policyUtils.globalPolicy( policyUtils.globalPolicy({
undefined, controller: name,
{ action,
handler: `${name}.${action}`, plugin,
}, })
undefined,
plugin
)
); );
// Return the controller. // Return the controller.
@ -109,14 +106,11 @@ module.exports = {
// Push global policy to make sure the permissions will work as expected. // Push global policy to make sure the permissions will work as expected.
// We're trying to detect the controller name. // We're trying to detect the controller name.
policiesFn.push( policiesFn.push(
policyUtils.globalPolicy( policyUtils.globalPolicy({
undefined, controller: name,
{ action,
handler: `${name}.${action}`, plugin,
}, })
undefined,
plugin
)
); );
// Make the query compatible with our controller by // Make the query compatible with our controller by
@ -149,14 +143,11 @@ module.exports = {
); );
} }
policiesFn[0] = policyUtils.globalPolicy( policiesFn[0] = policyUtils.globalPolicy({
undefined, controller: name,
{ action,
handler: `${name}.${action}`, plugin,
}, });
undefined,
plugin
);
} }
if (strapi.plugins['users-permissions']) { if (strapi.plugins['users-permissions']) {

View File

@ -130,14 +130,11 @@ module.exports = {
// Push global policy to make sure the permissions will work as expected. // Push global policy to make sure the permissions will work as expected.
policiesFn.push( policiesFn.push(
policyUtils.globalPolicy( policyUtils.globalPolicy({
undefined, controller: name,
{ action,
handler: `${name}.${action}`, plugin,
}, })
undefined,
plugin
)
); );
// Return the controller. // Return the controller.
@ -170,14 +167,11 @@ module.exports = {
// Push global policy to make sure the permissions will work as expected. // Push global policy to make sure the permissions will work as expected.
// We're trying to detect the controller name. // We're trying to detect the controller name.
policiesFn.push( policiesFn.push(
policyUtils.globalPolicy( policyUtils.globalPolicy({
undefined, controller: name,
{ action: isSingular ? 'findOne' : 'find',
handler: `${name}.${isSingular ? 'findOne' : 'find'}`, plugin,
}, })
undefined,
plugin
)
); );
// Make the query compatible with our controller by // Make the query compatible with our controller by
@ -221,14 +215,11 @@ module.exports = {
); );
} }
policiesFn[0] = policyUtils.globalPolicy( policiesFn[0] = policyUtils.globalPolicy({
undefined, controller: name,
{ action,
handler: `${name}.${action}`, plugin,
}, });
undefined,
plugin
);
} }
if (strapi.plugins['users-permissions']) { if (strapi.plugins['users-permissions']) {

View File

@ -1,31 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
/**
* Check that we're in a valid Strapi project.
*
* @returns {boolean}
*/
const isStrapiApp = () => {
const pathToPackageJSON = path.resolve(process.cwd(), 'package.json');
let validPackageJSON = true;
try {
require(pathToPackageJSON);
} catch (e) {
validPackageJSON = false;
}
return validPackageJSON;
};
module.exports = {
isStrapiApp
};

View File

@ -11,13 +11,10 @@ const sanitizeEntity = require('./sanitize-entity');
const parseType = require('./parse-type'); const parseType = require('./parse-type');
module.exports = { module.exports = {
cli: require('./cli'),
finder: require('./finder'), finder: require('./finder'),
knex: require('./knex'),
logger: require('./logger'), logger: require('./logger'),
models: require('./models'), models: require('./models'),
policy: require('./policy'), policy: require('./policy'),
regex: require('./regex'),
templateConfiguration: require('./templateConfiguration'), templateConfiguration: require('./templateConfiguration'),
convertRestQueryParams, convertRestQueryParams,
buildQuery, buildQuery,

View File

@ -1,68 +0,0 @@
'use strict';
/**
* Module dependencies
*/
/* eslint-disable prefer-template */
// Node.js core.
const fs = require('fs');
const path = require('path');
// Public node modules.
const _ = require('lodash');
/**
* Check if connection is valid
*/
module.exports = scope => {
// First, make sure the application we have access to
// the migration generator.
try {
require.resolve(path.resolve(scope.rootPath, 'node_modules', 'strapi-hook-knex'));
} catch (err) {
console.error('Impossible to call the Knex migration tool.');
console.error('You can install it with `$ npm install strapi-hook-knex --save`.');
process.exit(1);
}
// Try to access the databases config and register connections
// in the Knex query builder.
try {
fs.accessSync(path.resolve(scope.rootPath, 'config', 'environments', scope.environment, 'databases.json'), fs.F_OK | fs.R_OK);
} catch (err) {
console.error('No `databases.json` file detected at `' + path.resolve(scope.rootPath, 'config', 'environments', scope.environment) + '`.');
console.error(err);
process.exit(1);
}
// Save the connections and the current DB config.
scope.connections = JSON.parse(fs.readFileSync(path.resolve(scope.rootPath, 'config', 'environments', scope.environment, 'databases.json'))).connections;
scope.dbConfig = _.merge(scope.connections[scope.connection], {
migrations: {
directory: path.resolve(scope.rootPath, 'data', 'migrations', scope.connection)
},
seeds: {
directory: path.resolve(scope.rootPath, 'data', 'seeds', scope.connection)
}
});
// Make sure the specified connection exists in config.
if (!_.has(scope.connections, scope.connection)) {
console.error('No connection found for `' + scope.connection + '`.');
process.exit(1);
}
// Make sure the needed client is installed.
_.forEach(scope.connections, config => {
try {
scope.db = require(path.resolve(scope.rootPath, 'node_modules', 'knex'))(scope.dbConfig);
} catch (err) {
console.error('The client `' + config.client + '` is not installed.');
console.error(err);
process.exit(1);
}
});
};

View File

@ -1,9 +1,8 @@
// Public dependencies. // Public dependencies.
const _ = require('lodash'); const _ = require('lodash');
/* eslint-disable prefer-template */ /* eslint-disable prefer-template */
module.exports = { module.exports = {
get: function (policy, plugin, policies = [], endpoint, currentApiName) { get(policy, plugin, policies = [], endpoint, currentApiName) {
// Define global policy prefix. // Define global policy prefix.
const globalPolicyPrefix = 'global.'; const globalPolicyPrefix = 'global.';
const pluginPolicyPrefix = 'plugins.'; const pluginPolicyPrefix = 'plugins.';
@ -42,12 +41,14 @@ module.exports = {
) { ) {
// Plugin's policies can be used from app APIs with a specific syntax (`plugins.pluginName.policyName`). // Plugin's policies can be used from app APIs with a specific syntax (`plugins.pluginName.policyName`).
return policies.push( return policies.push(
this.parsePolicy(_.get( this.parsePolicy(
strapi.plugins, _.get(
policySplited[1] + strapi.plugins,
'.config.policies.' + policySplited[1] +
policySplited[2].toLowerCase() '.config.policies.' +
)) policySplited[2].toLowerCase()
)
)
); );
} else if ( } else if (
!_.startsWith(policy, globalPolicyPrefix, 0) && !_.startsWith(policy, globalPolicyPrefix, 0) &&
@ -61,10 +62,12 @@ module.exports = {
) { ) {
// Plugin policy used in the plugin itself. // Plugin policy used in the plugin itself.
return policies.push( return policies.push(
this.parsePolicy(_.get( this.parsePolicy(
strapi.plugins, _.get(
plugin + '.config.policies.' + policy.toLowerCase() strapi.plugins,
)) plugin + '.config.policies.' + policy.toLowerCase()
)
)
); );
} else if ( } else if (
!_.startsWith(policy, globalPolicyPrefix, 0) && !_.startsWith(policy, globalPolicyPrefix, 0) &&
@ -77,17 +80,21 @@ module.exports = {
) { ) {
// API policy used in the API itself. // API policy used in the API itself.
return policies.push( return policies.push(
this.parsePolicy(_.get( this.parsePolicy(
strapi.api, _.get(
currentApiName + '.config.policies.' + policy.toLowerCase() strapi.api,
)) currentApiName + '.config.policies.' + policy.toLowerCase()
)
)
); );
} }
strapi.log.error(`Ignored attempt to bind to ${endpoint} with unknown policy "${policy}"`); strapi.log.error(
`Ignored attempt to bind to ${endpoint} with unknown policy "${policy}"`
);
}, },
parsePolicy: (policy) => { parsePolicy(policy) {
if (_.isFunction(policy)) { if (_.isFunction(policy)) {
return policy; return policy;
} }
@ -97,18 +104,18 @@ module.exports = {
// Middleware used for every routes. // Middleware used for every routes.
// Expose the endpoint in `this`. // Expose the endpoint in `this`.
globalPolicy: (endpoint, value, route = {}, plugin) => { globalPolicy({ method, endpoint, controller, action, plugin }) {
return async (ctx, next) => { return async (ctx, next) => {
ctx.request.route = { ctx.request.route = {
endpoint: _.trim(endpoint), endpoint: `${method} ${endpoint}`,
controller: value.handler.split('.')[0].toLowerCase(), controller,
action: value.handler.split('.')[1].toLowerCase(), action,
splittedEndpoint: _.trim(route.endpoint), splittedEndpoint: endpoint,
verb: route.verb && _.trim(route.verb.toLowerCase()), verb: method,
plugin plugin,
}; };
await next(); await next();
}; };
} },
}; };

View File

@ -1,31 +0,0 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
/**
* Detect HTTP verb in an expression.
*
* @api private
*/
exports.detectRoute = endpoint => {
const verbExpr = /^(all|get|post|put|delete|trace|options|connect|patch|head|redirect)\s+/i;
let verb = _.last(endpoint.match(verbExpr) || []) || '';
verb = verb.toLowerCase();
// If a verb was specified, eliminate the verb from the original string.
if (verb) {
endpoint = endpoint.replace(verbExpr, '');
}
// Return the verb and the endpoint.
return {
verb,
endpoint
};
};

View File

@ -1,18 +1,10 @@
const { join } = require('path'); const { join } = require('path');
const { existsSync } = require('fs-extra'); const { existsSync } = require('fs-extra');
const ora = require('ora'); const ora = require('ora');
const { cyan } = require('chalk');
const execa = require('execa'); const execa = require('execa');
const { cli } = require('strapi-utils');
const findPackagePath = require('../load/package-path'); const findPackagePath = require('../load/package-path');
module.exports = async plugins => { module.exports = async plugins => {
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi install')} can only be used inside a Strapi project.`
);
}
const loader = ora(); const loader = ora();
const dir = process.cwd(); const dir = process.cwd();

View File

@ -4,18 +4,10 @@ const { join } = require('path');
const { existsSync, rmdirSync } = require('fs-extra'); const { existsSync, rmdirSync } = require('fs-extra');
const ora = require('ora'); const ora = require('ora');
const execa = require('execa'); const execa = require('execa');
const { cyan } = require('chalk');
const inquirer = require('inquirer'); const inquirer = require('inquirer');
const { cli } = require('strapi-utils');
const findPackagePath = require('../load/package-path'); const findPackagePath = require('../load/package-path');
module.exports = async (plugins, { deleteFiles }) => { module.exports = async (plugins, { deleteFiles }) => {
if (!cli.isStrapiApp()) {
return console.log(
`⛔️ ${cyan('strapi install')} can only be used inside a Strapi project.`
);
}
const answers = await inquirer.prompt([ const answers = await inquirer.prompt([
{ {
type: 'confirm', type: 'confirm',

View File

@ -7,13 +7,13 @@
// Public node modules. // Public node modules.
const _ = require('lodash'); const _ = require('lodash');
const Router = require('koa-router'); const Router = require('koa-router');
const createEndpointComposer = require('./utils/composeEndpoint');
/** /**
* Router hook * Router hook
*/ */
module.exports = strapi => { module.exports = strapi => {
const composeEndpoint = require('./utils/composeEndpoint')(strapi); const composeEndpoint = createEndpointComposer(strapi);
return { return {
/** /**
@ -22,7 +22,7 @@ module.exports = strapi => {
initialize() { initialize() {
_.forEach(strapi.config.routes, value => { _.forEach(strapi.config.routes, value => {
composeEndpoint(value, null, strapi.router); composeEndpoint(value, { router: strapi.router });
}); });
strapi.router.prefix( strapi.router.prefix(
@ -37,7 +37,7 @@ module.exports = strapi => {
}); });
_.forEach(strapi.admin.config.routes, value => { _.forEach(strapi.admin.config.routes, value => {
composeEndpoint(value, null, router); composeEndpoint(value, { router });
}); });
// Mount admin router on Strapi router // Mount admin router on Strapi router
@ -46,9 +46,9 @@ module.exports = strapi => {
if (strapi.plugins) { if (strapi.plugins) {
// Parse each plugin's routes. // Parse each plugin's routes.
_.forEach(strapi.plugins, (plugin, name) => { _.forEach(strapi.plugins, (plugin, pluginName) => {
const router = new Router({ const router = new Router({
prefix: `/${name}`, prefix: `/${pluginName}`,
}); });
// Exclude routes with prefix. // Exclude routes with prefix.
@ -60,14 +60,17 @@ module.exports = strapi => {
_.forEach( _.forEach(
_.omit(plugin.config.routes, _.keys(excludedRoutes)), _.omit(plugin.config.routes, _.keys(excludedRoutes)),
value => { value => {
composeEndpoint(value, name, router); composeEndpoint(value, { plugin: pluginName, router });
} }
); );
// /!\ Could override main router's routes. // /!\ Could override main router's routes.
if (!_.isEmpty(excludedRoutes)) { if (!_.isEmpty(excludedRoutes)) {
_.forEach(excludedRoutes, value => { _.forEach(excludedRoutes, value => {
composeEndpoint(value, name, strapi.router); composeEndpoint(value, {
plugin: pluginName,
router: strapi.router,
});
}); });
} }

View File

@ -2,25 +2,24 @@
const _ = require('lodash'); const _ = require('lodash');
const compose = require('koa-compose'); const compose = require('koa-compose');
const createRouteChecker = require('./routerChecker');
module.exports = strapi => { module.exports = strapi => {
const routerChecker = require('./routerChecker')(strapi); const routerChecker = createRouteChecker(strapi);
return (value, plugin, router) => { return (value, { plugin, router }) => {
if (_.isEmpty(_.get(value, 'method')) || _.isEmpty(_.get(value, 'path'))) { if (_.isEmpty(_.get(value, 'method')) || _.isEmpty(_.get(value, 'path'))) {
return; return;
} }
const endpoint = `${value.method} ${value.path}`; const { method, endpoint, policies, action } = routerChecker(value, plugin);
const { policies, action } = routerChecker(value, endpoint, plugin);
if (_.isUndefined(action) || !_.isFunction(action)) { if (_.isUndefined(action) || !_.isFunction(action)) {
return strapi.log.warn( return strapi.log.warn(
`Ignored attempt to bind route '${endpoint}' to unknown controller/action.` `Ignored attempt to bind route '${value.method} ${value.path}' to unknown controller/action.`
); );
} }
router[value.method.toLowerCase()](value.path, compose(policies), action); router[method](endpoint, compose(policies), action);
}; };
}; };

View File

@ -8,11 +8,15 @@
const _ = require('lodash'); const _ = require('lodash');
// Strapi utilities. // Strapi utilities.
const { finder, regex, policy: policyUtils } = require('strapi-utils'); const { finder, policy: policyUtils } = require('strapi-utils');
const getMethod = route => _.trim(_.toLower(route.method));
const getEndpoint = route => _.trim(route.path);
module.exports = strapi => module.exports = strapi =>
function routerChecker(value, endpoint, plugin) { function routerChecker(value, plugin) {
const route = regex.detectRoute(endpoint); const method = getMethod(value);
const endpoint = getEndpoint(value);
// Define controller and action names. // Define controller and action names.
const [controllerName, actionName] = _.trim(value.handler).split('.'); const [controllerName, actionName] = _.trim(value.handler).split('.');
@ -41,7 +45,15 @@ module.exports = strapi =>
const policies = []; const policies = [];
// Add the `globalPolicy`. // Add the `globalPolicy`.
policies.push(policyUtils.globalPolicy(endpoint, value, route, plugin)); policies.push(
policyUtils.globalPolicy({
controller,
action: actionName,
method,
endpoint,
plugin,
})
);
// Allow string instead of array of policies. // Allow string instead of array of policies.
if ( if (
@ -56,7 +68,13 @@ module.exports = strapi =>
!_.isEmpty(_.get(value, 'config.policies')) !_.isEmpty(_.get(value, 'config.policies'))
) { ) {
_.forEach(value.config.policies, policy => { _.forEach(value.config.policies, policy => {
policyUtils.get(policy, plugin, policies, endpoint, currentApiName); policyUtils.get(
policy,
plugin,
policies,
`${method} ${endpoint}`,
currentApiName
);
}); });
} }
@ -70,7 +88,8 @@ module.exports = strapi =>
}); });
return { return {
route, method,
endpoint,
policies, policies,
action, action,
}; };