Normalize usage of strapi.config.get

Signed-off-by: Alexandre Bodin <bodin.alex@gmail.com>
This commit is contained in:
Alexandre Bodin 2020-04-09 16:27:29 +02:00
parent 3cf3570afb
commit 1cb92daa77
8 changed files with 145 additions and 153 deletions

View File

@ -22,10 +22,10 @@ const isValidPluginName = plugin => {
module.exports = {
async init(ctx) {
const uuid = _.get(strapi, ['config', 'uuid'], false);
const currentEnvironment = strapi.app.env;
const autoReload = _.get(strapi, ['config', 'autoReload'], false);
const strapiVersion = _.get(strapi.config, 'info.strapi', null);
const uuid = strapi.config.get('uuid', false);
const autoReload = strapi.config.get('autoReload', false);
const strapiVersion = strapi.config.get('info.strapi', null);
return ctx.send({
data: { uuid, currentEnvironment, autoReload, strapiVersion },
@ -43,7 +43,7 @@ module.exports = {
async getStrapiVersion(ctx) {
try {
const strapiVersion = _.get(strapi.config, 'info.strapi', null);
const strapiVersion = strapi.config.get('info.strapi', null);
return ctx.send({ strapiVersion });
} catch (err) {
return ctx.badRequest(null, [{ messages: [{ id: 'The version is not available' }] }]);
@ -52,7 +52,7 @@ module.exports = {
async getGaConfig(ctx) {
try {
ctx.send({ uuid: _.get(strapi.config, 'uuid', false) });
ctx.send({ uuid: strapi.config.get('uuid', false) });
} catch (err) {
ctx.badRequest(null, [{ messages: [{ id: 'An error occurred' }] }]);
}

View File

@ -36,7 +36,7 @@ module.exports = strapi => {
return {
async beforeInitialize() {
// Try to inject this hook just after the others hooks to skip the router processing.
if (!_.get(strapi.config.hook.load, 'after')) {
if (!strapi.config.get('hook.load.after')) {
_.set(strapi.config.hook.load, 'after', []);
}

View File

@ -21,6 +21,10 @@ module.exports = (initialConfig = {}) => {
return this;
},
has(path) {
return _.has(_config, path);
},
merge(...args) {
_.merge(_config, ...args);
return this;

View File

@ -15,6 +15,8 @@ const getPrefixedDeps = require('../../utils/get-prefixed-dependencies');
const loadPolicies = require('../load-policies');
const loadFunctions = require('../load-functions');
const { version: strapiVersion } = require(path.join(__dirname, '../../../package.json'));
const CONFIG_PATHS = {
admin: 'admin',
api: 'api',
@ -30,6 +32,34 @@ const CONFIG_PATHS = {
views: 'views',
};
const defaultConfig = {
server: {
host: process.env.HOST || process.env.HOSTNAME || 'localhost',
port: process.env.PORT || 1337,
proxy: { enabled: false },
cron: { enabled: false },
admin: { autoOpen: false },
},
admin: {},
middleware: {
timeout: 1000,
load: {
before: ['responseTime', 'logger', 'cors', 'responses', 'gzip'],
order: [],
after: ['parser', 'router'],
},
settings: {},
},
hook: {
timeout: 1000,
load: { before: [], order: [], after: [] },
settings: {},
},
routes: {},
functions: {},
policies: {},
};
module.exports = (dir, initialConfig = {}) => {
const { autoReload = false, serveAdminPanel = true } = initialConfig;
@ -37,48 +67,31 @@ module.exports = (dir, initialConfig = {}) => {
const configDir = path.resolve(dir || process.cwd(), 'config');
const defaultConfig = {
const rootConfig = {
launchedAt: Date.now(),
appPath: dir,
paths: CONFIG_PATHS,
serveAdminPanel,
autoReload,
environment: process.env.NODE_ENV,
server: {
host: process.env.HOST || process.env.HOSTNAME || 'localhost',
port: process.env.PORT || 1337,
proxy: { enabled: false },
cron: { enabled: false },
admin: { autoOpen: false },
uuid: _.get(pkgJSON, 'strapi.uuid'),
info: {
...pkgJSON,
strapi: strapiVersion,
},
admin: {},
paths: CONFIG_PATHS,
middleware: {
timeout: 1000,
load: {
before: ['responseTime', 'logger', 'cors', 'responses', 'gzip'],
order: [],
after: ['parser', 'router'],
},
settings: {},
},
hook: {
timeout: 1000,
load: { before: [], order: [], after: [] },
settings: {},
},
routes: {},
info: pkgJSON,
policies: loadPolicies(path.resolve(configDir, 'policies')),
functions: loadFunctions(path.resolve(configDir, 'functions')),
installedPlugins: getPrefixedDeps('strapi-plugin', pkgJSON),
installedMiddlewares: getPrefixedDeps('strapi-middleware', pkgJSON),
installedHooks: getPrefixedDeps('strapi-hook', pkgJSON),
};
const baseConfig = loadConfigDir(configDir);
const baseConfig = {
...loadConfigDir(configDir),
policies: loadPolicies(path.resolve(configDir, 'policies')),
functions: loadFunctions(path.resolve(configDir, 'functions')),
};
const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV);
const envConfig = loadConfigDir(envDir);
return createConfigProvider(_.merge(defaultConfig, baseConfig, envConfig));
return createConfigProvider(_.merge(rootConfig, defaultConfig, baseConfig, envConfig));
};

View File

@ -17,18 +17,15 @@ const pickSchema = model => {
};
module.exports = function(strapi) {
// Retrieve Strapi version.
strapi.config.uuid = _.get(strapi.config.info, 'strapi.uuid', '');
strapi.config.info.strapi = require(__dirname + '/../../package.json').version;
// Set connections.
strapi.connections = {};
const defaultConnection = strapi.config.database.defaultConnection;
const defaultConnection = strapi.config.get('database.defaultConnection');
// Set current connections.
strapi.config.connections = _.get(strapi.config, 'database.connections', {});
strapi.config.connections = strapi.config.get('database.connections', {});
// FIXME:
if (_.get(strapi.config, 'language.enabled')) {
strapi.config.language.locales = Object.keys(_.get(strapi.config, 'locales', {}));
}

View File

@ -19,7 +19,7 @@ module.exports = strapi => {
*/
initialize() {
_.forEach(_.keys(strapi.config.functions.cron), task => {
_.forEach(_.keys(strapi.config.get('functions.cron', {})), task => {
cron.scheduleJob(task, strapi.config.functions.cron[task]);
});
},

View File

@ -8,7 +8,7 @@ module.exports = strapi => {
strapi.app.use(async (ctx, next) => {
await next();
const responseFn = _.get(strapi.functions, ['responses', ctx.status]);
const responseFn = strapi.config.get(['functions', 'responses', ctx.status]);
if (_.isFunction(responseFn)) {
await responseFn(ctx);
}

View File

@ -1,43 +1,114 @@
'use strict';
/**
* Module dependencies
*/
// Core modules
const path = require('path');
const _ = require('lodash');
const session = require('koa-session');
/**
* Session hook
* Session middleware
*/
module.exports = strapi => {
const hook = {
/**
* Initialize the hook
*/
const requireStore = store => {
return require(path.resolve(strapi.config.appPath, 'node_modules', 'koa-' + store));
};
const defineStore = session => {
if (_.isEmpty(_.get(session, 'client'))) {
return strapi.log.error(
'(middleware:session) please provide a valid client to store session'
);
} else if (_.isEmpty(_.get(session, 'connection'))) {
return strapi.log.error(
'(middleware:session) please provide connection for the session store'
);
} else if (strapi.config.get(`database.connections.${session.connection}`)) {
return strapi.log.error(
'(middleware:session) please provide a valid connection for the session store'
);
}
session.settings = strapi.config.get(`database.connections.${session.connection}`);
// Define correct store name to avoid require to failed.
switch (session.client.toLowerCase()) {
case 'redis': {
const store = requireStore('redis');
session.settings.db = session.settings.database;
return store(session.settings);
}
case 'mysql': {
const Store = requireStore('mysql-session');
return new Store(session.settings);
}
case 'mongo': {
const Store = requireStore('generic-session-mongo');
session.settings.db = session.settings.database;
return new Store(session.settings);
}
case 'postgresql': {
const Store = requireStore('pg-session');
return new Store(session.settings, session.options);
}
case 'rethink': {
const Store = requireStore('generic-session-rethinkdb');
session.settings.dbName = session.settings.database;
session.settings.tableName = session.settings.table;
const sessionStore = new Store({
connection: session.settings,
});
// Create the DB, tables and indexes to store sessions.
sessionStore.setup();
return sessionStore;
}
case 'sqlite': {
const Store = requireStore('sqlite3-session');
return new Store(session.fileName, session.options);
}
case 'sequelize': {
const Store = requireStore('generic-session-sequelize');
// Sequelize needs to be instantiated.
if (!_.isObject(strapi.sequelize)) {
return null;
}
return new Store(strapi.sequelize, session.options);
}
default: {
return null;
}
}
};
return {
initialize() {
strapi.app.keys =
_.get(strapi.config.middleware.settings.session, 'secretKeys') ||
strapi.config.hooks.session.secretKeys;
strapi.app.keys = strapi.config.get('middleware.settings.session.secretKeys');
if (
_.has(strapi.config.middleware.settings.session, 'client') &&
_.isString(strapi.config.middleware.settings.session.client) &&
strapi.config.middleware.settings.session.client !== 'cookie'
) {
const store = hook.defineStore(strapi.config.middleware.settings.session);
const store = defineStore(strapi.config.middleware.settings.session);
if (!_.isEmpty(store)) {
// Options object contains the defined store, the custom hooks configurations
// Options object contains the defined store, the custom middlewares configurations
// and also the function which are located to `./config/functions/session.js`
const options = _.assign(
{
store,
},
strapi.config.hook.session,
strapi.config.middleware.settings.session
);
@ -54,10 +125,7 @@ module.exports = strapi => {
_.isString(strapi.config.middleware.settings.session.client) &&
strapi.config.middleware.settings.session.client === 'cookie'
) {
const options = _.assign(
strapi.config.hook.session,
strapi.config.middleware.settings.session
);
const options = _.assign(strapi.config.middleware.settings.session);
strapi.app.use(session(options, strapi.app));
strapi.app.use((ctx, next) => {
@ -68,95 +136,5 @@ module.exports = strapi => {
});
}
},
defineStore(session) {
if (_.isEmpty(_.get(session, 'client'))) {
return strapi.log.error(
'(middleware:session) please provide a valid client to store session'
);
} else if (_.isEmpty(_.get(session, 'connection'))) {
return strapi.log.error(
'(middleware:session) please provide connection for the session store'
);
} else if (strapi.config.get(`database.connections.${session.connection}`)) {
return strapi.log.error(
'(middleware:session) please provide a valid connection for the session store'
);
}
session.settings = strapi.config.get(`database.connections.${session.connection}`);
// Define correct store name to avoid require to failed.
switch (session.client.toLowerCase()) {
case 'redis': {
const store = hook.requireStore('redis');
session.settings.db = session.settings.database;
return store(session.settings);
}
case 'mysql': {
const Store = hook.requireStore('mysql-session');
return new Store(session.settings);
}
case 'mongo': {
const Store = hook.requireStore('generic-session-mongo');
session.settings.db = session.settings.database;
return new Store(session.settings);
}
case 'postgresql': {
const Store = hook.requireStore('pg-session');
return new Store(session.settings, session.options);
}
case 'rethink': {
const Store = hook.requireStore('generic-session-rethinkdb');
session.settings.dbName = session.settings.database;
session.settings.tableName = session.settings.table;
const sessionStore = new Store({
connection: session.settings,
});
// Create the DB, tables and indexes to store sessions.
sessionStore.setup();
return sessionStore;
}
case 'sqlite': {
const Store = hook.requireStore('sqlite3-session');
return new Store(session.fileName, session.options);
}
case 'sequelize': {
const Store = hook.requireStore('generic-session-sequelize');
// Sequelize needs to be instantiated.
if (!_.isObject(strapi.sequelize)) {
return null;
}
return new Store(strapi.sequelize, session.options);
}
default: {
return null;
}
}
},
requireStore(store) {
// eslint-disable-next-line no-useless-catch
try {
return require(path.resolve(strapi.config.appPath, 'node_modules', 'koa-' + store));
} catch (err) {
throw err;
}
},
};
return hook;
};