背景
存在这样一个场景:有一个config参数在模块的前端和后端都会用到。一般的解决方案是在模块的前端和后端分别设置config参数。这种实现方式存在以下两个问题:
繁琐
:设置参数需要做两遍,如果用项目参数来覆盖模块参数也需要做两遍不一致
:由于后端的config参数支持实例级别
的不同设置,而前端没有实例级别
的设置机制,最终导致前后端config参数值不一致
后端覆盖前端
CabloyJS在后端config中单独定义了一个configFront
节点。通过此节点配置的config参数,会自动发往前端,与前端的config参数合并,从而轻松解决了前面提到的两个问题
比如,我们希望在本地开发环境
下,在登录页面不必输入验证码
就可以进入系统。 验证码
机制是由模块a-captcha
提供的,我们看看模块a-captcha
是如何处理的
1. 定义configFront
节点
src/module-system/a-captcha/backend/src/config/config.js
- 1// eslint-disable-next-line
- 2module.exports = appInfo => {
- 3 const config = {};
- 4
- 5 // configFront
- 6 config.configFront = {
- 7 local: {
- 8 disabled: false,
- 9 },
- 10 };
- 11
- 12 return config;
- 13};
名称 | 说明 |
---|---|
local.disabled | 在本地开发环境是否禁用验证码 机制 |
2. 后端访问config参数
src/module-system/a-captcha/backend/src/bean/middleware.captchaVerify.js
- 1...
- 2const moduleInfo = ctx.app.meta.mockUtil.parseInfoFromPackage(__dirname);
- 3...
- 4// local.disabled
- 5const configModule = ctx.config.module(moduleInfo.relativeName);
- 6if (ctx.app.meta.isLocal && configModule.configFront.local.disabled) {
- 7 // next
- 8 return await next();
- 9}
- 10...
先判断是否处于本地开发环境
,再判断configFront.local.disabled
是否为true
,如果判断二者均为true
,则跳过验证环节,直接调用next
3. 前端访问config参数
- 1# 本模块内部访问
- 2const disabled = this.$config.local.disabled;
- 3# 跨模块访问
- 4const disabled = this.$meta.config.modules['a-captcha'].local.disabled;
也就是说,仍然延续config前端参数的访问方式,参见:模块前端开发-Config
4. 项目参数覆盖模块参数
由于参数configFront.local.disabled
是在模块a-captcha
的后端设置的,而且默认值为false
。如果我们想把该值设置为true
,那么就需要通过项目参数来覆盖模块参数
src/backend/config/config.local.js
- 1 // module config
- 2 config.modules = {
- 3 'a-captcha': {
- 4 configFront: {
- 5 local: {
- 6 disabled: true,
- 7 },
- 8 },
- 9 },
- 10 };
参见:后端配置-覆盖模块参数
评论: