Kong -- 如何为数组编写实体检查 #6989

概要

我正在基于官方的速率限制插件开发自己的速率限制插件。

原始模式如下所示:

fields = {
    { config = {
        type = "record",
        fields = {
          { second = { type = "number", gt = 0 }, },
          { minute = { type = "number", gt = 0 }, },
        }
...
      },
    },

我的模式如下所示:

    { config = {
        type = "record",
        fields = {
          { plans = {
            type = "array",
            elements = {
              type = "record",
              fields = {
                { second = { type = "number", gt = 0 }, },
                { minute = { type = "number", gt = 0 }, },
              }
            },
          },},
        },
        custom_validator = validate_periods_order,
      },
    },

你可以看到第一个字段叫做"plans",它的类型是一个数组,这意味着我将有config.plans[0].secondconfig.plans[0].minute,...,而原始值是config.second

下面是速率限制的原始entity_checks函数,我不知道如何将其重写以匹配我的模式,因为它从简单的"record"类型变成了"array"类型

entity_checks = {
    { at_least_one_of = { "config.second", "config.minute", "config.hour", "config.day", "config.month", "config.year" } },
    { conditional = {
      if_field = "config.policy", if_match = { eq = "config.redis" },
      then_field = "config.redis_host", then_match = { required = true },
    } },
    { conditional = {
      if_field = "config.policy", if_match = { eq = "config.redis" },
      then_field = "config.redis_port", then_match = { required = true },
    } },
    { conditional = {
      if_field = "config.policy", if_match = { eq = "config.redis" },
      then_field = "config.redis_timeout", then_match = { required = true },
    } },
  },
点赞
用户4605105
用户4605105

计划创建一个本地模式

local plan_schema = {
  type = "record",
  fields = {
    { second = { type = "number", gt = 0 }, },
    { minute = { type = "number", gt = 0 }, },
  },
  custom_validator = validate_periods_order,
  entity_checks = {
    { at_least_one_of = { "second", "minute" } },
  }
}

然后在您的配置中将 plans 设置为 plan 数组

return {
  name = plugin_name,
  fields = {
    { consumer = typedefs.no_consumer },
    { protocols = typedefs.protocols_http },
    { config = {
      type = "record",
      fields = {
        { plans = {
          type = "array",
          elements =  plan_schema ,
        } },
    } },
  },
}
2021-05-18 22:55:35