背景

存在这样一个场景:有一个config参数在模块的前端和后端都会用到。一般的解决方案是在模块的前端和后端分别设置config参数。这种实现方式存在以下两个问题:

  1. 繁琐:设置参数需要做两遍,如果用项目参数来覆盖模块参数也需要做两遍
  2. 不一致:由于后端的config参数支持实例级别的不同设置,而前端没有实例级别的设置机制,最终导致前后端config参数值不一致

后端覆盖前端

CabloyJS在后端config中单独定义了一个configFront节点。通过此节点配置的config参数,会自动发往前端,与前端的config参数合并,从而轻松解决了前面提到的两个问题

比如,我们希望在本地开发环境下,在登录页面不必输入验证码就可以进入系统。 验证码机制是由模块a-captcha提供的,我们看看模块a-captcha是如何处理的

1. 定义configFront节点

src/module-system/a-captcha/backend/src/config/config.js

  1. 1// eslint-disable-next-line
  2. 2module.exports = appInfo => {
  3. 3 const config = {};
  4. 4
  5. 5 // configFront
  6. 6 config.configFront = {
  7. 7 local: {
  8. 8 disabled: false,
  9. 9 },
  10. 10 };
  11. 11
  12. 12 return config;
  13. 13};
名称 说明
local.disabled 在本地开发环境是否禁用验证码机制

2. 后端访问config参数

src/module-system/a-captcha/backend/src/bean/middleware.captchaVerify.js

  1. 1...
  2. 2const moduleInfo = ctx.app.meta.mockUtil.parseInfoFromPackage(__dirname);
  3. 3...
  4. 4// local.disabled
  5. 5const configModule = ctx.config.module(moduleInfo.relativeName);
  6. 6if (ctx.app.meta.isLocal && configModule.configFront.local.disabled) {
  7. 7 // next
  8. 8 return await next();
  9. 9}
  10. 10...

先判断是否处于本地开发环境,再判断configFront.local.disabled是否为true,如果判断二者均为true,则跳过验证环节,直接调用next

3. 前端访问config参数

  1. 1# 本模块内部访问
  2. 2const disabled = this.$config.local.disabled;
  3. 3# 跨模块访问
  4. 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. 1 // module config
  2. 2 config.modules = {
  3. 3 'a-captcha': {
  4. 4 configFront: {
  5. 5 local: {
  6. 6 disabled: true,
  7. 7 },
  8. 8 },
  9. 9 },
  10. 10 };

参见:后端配置-覆盖模块参数