Add some lazy loading

This commit is contained in:
Alexandre Bodin 2021-09-03 11:11:37 +02:00
parent e4abd6f4dc
commit d4eef8ea75
12 changed files with 79 additions and 50 deletions

View File

@ -2,7 +2,6 @@
const _ = require('lodash');
const { getOr } = require('lodash/fp');
const strapiGenerators = require('@strapi/generators');
const { nameToSlug, contentTypes: contentTypesUtils } = require('@strapi/utils');
const { formatAttributes, replaceTemporaryUIDs } = require('../utils/attributes');
@ -127,6 +126,7 @@ const createContentType = async ({ contentType, components = [] }, options = {})
* @param {string} name
*/
const generateAPI = ({ name, kind = 'collectionType' }) => {
const strapiGenerators = require('@strapi/generators');
return strapiGenerators.generate('api', { id: nameToSlug(name), kind }, { dir: strapi.dir });
};

View File

@ -321,6 +321,7 @@ class Strapi {
await this.runLifecyclesFunctions(LIFECYCLES.BOOTSTRAP);
this.isLoaded = true;
return this;
}

View File

@ -87,6 +87,7 @@ const applyUserConfig = plugins => {
const loadPlugins = async strapi => {
const plugins = {};
const enabledPlugins = await getEnabledPlugins(strapi);
for (const pluginName in enabledPlugins) {
@ -94,6 +95,7 @@ const loadPlugins = async strapi => {
const pluginServer = loadConfigFile(join(enabledPlugin.pathToPlugin, 'strapi-server.js'));
plugins[pluginName] = defaultsDeep(defaultPlugin, pluginServer);
}
// TODO: validate plugin format
applyUserConfig(plugins);
await applyUserExtension(plugins);

View File

@ -1,6 +1,6 @@
'use strict';
const { toLower, castArray, trim } = require('lodash/fp');
const { toLower, castArray, trim, prop } = require('lodash/fp');
const compose = require('koa-compose');
const { validateRouteConfig } = require('./route');
@ -9,6 +9,42 @@ const { resolvePolicies } = require('./policy');
const getMethod = route => trim(toLower(route.method));
const getPath = route => trim(route.path);
const getHandler = prop('handler');
const createRouteInfoMiddleware = ({ method, path, handler }, { pluginName }) => {
return (ctx, next) => {
if (typeof handler === 'string') {
const [controllerName, actionName] = handler.split('.');
ctx.request.route = {
endpoint: `${method} ${path}`,
controller: toLower(controllerName),
action: toLower(actionName),
verb: toLower(method),
plugin: pluginName,
};
}
return next();
};
};
const createAuthMiddleware = () => {
return (ctx, next) => {
return next();
// if (routeConfig.auth && routeConfig.auth.public === true) {
// return next();
// }
// const { credentials, isAuthenticated = false } = ({} = ctx.state.auth);
// if (!isAuthenticated) {
// throw new ctx.unauthorized();
// }
// check credentials scope with routeConfig scope
};
};
module.exports = strapi => {
return (routeConfig, { pluginName, router, apiName }) => {
@ -17,45 +53,30 @@ module.exports = strapi => {
try {
const method = getMethod(routeConfig);
const path = getPath(routeConfig);
const handler = getHandler(routeConfig);
const middlewares = resolveMiddlewares(routeConfig);
const policies = resolvePolicies(routeConfig, { pluginName, apiName });
const routeInfo = (ctx, next) => {
if (typeof routeConfig.handler === 'string') {
const [controllerName, actionName] = routeConfig.handler.split('.');
ctx.request.route = {
endpoint: `${method} ${path}`,
controller: toLower(controllerName),
action: toLower(actionName),
verb: toLower(method),
plugin: pluginName,
};
}
const routeInfoMiddleware = createRouteInfoMiddleware(
{ method, path, handler },
{ pluginName }
);
return next();
};
const auth = (ctx, next) => {
return next();
// if (routeConfig.auth && routeConfig.auth.public === true) {
// return next();
// }
// const { credentials, isAuthenticated = false } = ({} = ctx.state.auth);
// if (!isAuthenticated) {
// throw new ctx.unauthorized();
// }
// check credentials scope with routeConfig scope
};
// we can add this as a root middleware
const authMiddleware = createAuthMiddleware();
const action = getAction(routeConfig, { pluginName, apiName }, strapi);
const handler = compose([routeInfo, auth, ...policies, ...middlewares, ...castArray(action)]);
router[method](path, handler);
const routeHandler = compose([
routeInfoMiddleware,
authMiddleware,
...policies,
...middlewares,
...castArray(action),
]);
router[method](path, routeHandler);
} catch (error) {
throw new Error(
`Error creating endpoint ${routeConfig.method} ${routeConfig.path}: ${error.message}`

View File

@ -12,6 +12,7 @@ const resolveMiddlewares = route => {
return middlewareConfig;
}
// TODO: this won't work until we have the new middleware formats
const middleware = strapi.middleware(middlewareConfig);
if (!middleware) {

View File

@ -11,7 +11,6 @@ const path = require('path');
// Public dependencies.
const fs = require('fs-extra');
const cheerio = require('cheerio');
const _ = require('lodash');
const koaStatic = require('koa-static');
@ -101,6 +100,9 @@ module.exports = {
},
async loginView(ctx, next) {
// lazy require cheerio
const cheerio = require('cheerio');
const { error } = ctx.query;
try {

View File

@ -2,7 +2,6 @@
const path = require('path');
const _ = require('lodash');
const swaggerUi = require('swagger-ui-dist');
const koaStatic = require('koa-static');
const initialRoutes = [];
@ -17,6 +16,8 @@ module.exports = {
},
initialize() {
const swaggerUi = require('swagger-ui-dist');
// Find the plugins routes.
strapi.plugins.documentation.routes = strapi.plugins.documentation.routes.map(
(route, index) => {

View File

@ -9,7 +9,6 @@
/* eslint-disable no-useless-escape */
const crypto = require('crypto');
const _ = require('lodash');
const grant = require('grant-koa');
const { sanitizeEntity } = require('@strapi/utils');
const { getService } = require('../utils');
@ -232,6 +231,8 @@ module.exports = {
},
async connect(ctx, next) {
const grant = require('grant-koa');
const grantConfig = await strapi
.store({
environment: '',

View File

@ -69,6 +69,7 @@ module.exports = async (ctx, next) => {
const permission = await strapi.query('plugin::users-permissions.permission').findOne({
where: {
role: { id: role.id },
// TODO: Refactor u&p to use just one action name
type: route.plugin || 'application',
controller: route.controller,
action: route.action,

View File

@ -1,12 +1,8 @@
'use strict';
const lazyRateLimit = {
get RateLimit() {
return require('koa2-ratelimit').RateLimit;
},
};
module.exports = async (ctx, next) => {
const ratelimit = require('koa2-ratelimit').RateLimit;
const message = [
{
messages: [
@ -18,7 +14,7 @@ module.exports = async (ctx, next) => {
},
];
return lazyRateLimit.RateLimit.middleware(
return ratelimit.middleware(
Object.assign(
{},
{

View File

@ -6,15 +6,17 @@
// Public node modules.
const _ = require('lodash');
const request = require('request');
// Purest strategies.
const purest = require('purest')({ request });
const purestConfig = require('@purest/providers');
const { getAbsoluteServerUrl } = require('@strapi/utils');
const jwt = require('jsonwebtoken');
const { getAbsoluteServerUrl } = require('@strapi/utils');
module.exports = ({ strapi }) => {
// lazy load heavy dependencies
const request = require('request');
// Purest strategies.
const purest = require('purest')({ request });
const purestConfig = require('@purest/providers');
/**
* Helper to get profiles
*

View File

@ -1,7 +1,7 @@
'use strict';
const _ = require('lodash');
const request = require('request');
const { getService } = require('../utils');
const DEFAULT_PERMISSIONS = [
@ -118,6 +118,7 @@ module.exports = ({ strapi }) => ({
},
getPlugins(lang = 'en') {
const request = require('request');
return new Promise(resolve => {
request(
{