限制数组类型的值

huangapple go评论76阅读模式
英文:

Restrict values of an array type

问题

抱歉,我只能翻译您提供的自然语言文本。代码部分将保持原样。

以下是您提供的文本的翻译:

"这实际上不能更容易,但我无论如何都找不到解决方案。

我想从前端接受一个带有受限值的数组。

具有以下jsonschema:

const models = {
  type: "string",
  enum: [
    "model1",
    "model2",
    "model3",
  ],
};

const cleanQ = {
  type: "object",
  required: ["models"],
  properties: {
    models: {
      type: "array",
      anyOf: [models],
    },
  },
  additionalProperties: false,
};

我可以在前端获得一个如下的数组输入类型:

限制数组类型的值

它只接受一个单一值,在后端它会被转换为一个字符串值。如果我添加另一个正确的值,我会得到以下错误:

> 请求未通过验证:错误:querystring/models 必须等于允许的值之一,querystring/models 必须与 anyOf 中的模式匹配。

英文:

It cannot be easier, frankly, however I cannot find the solution anywhere.

I would like to accept an array from the front, with restricted values.

Having the following jsonschema:

const models = {
  type: "string",
  enum: [
    "model1",
    "model2",
    "model3",
  ],
};

const cleanQ = {
  type: "object",
  required: ["models"],
  properties: {
    models: {
      type: "array",
      anyOf: [models],
    },
  },
  additionalProperties: false,
};

I can get an array input type on the front like the following:

限制数组类型的值

that only accepts one single value, and in the back it is transformed as a string value. If I add another correct value, I have the following error:

> Request failed validation: Error: querystring/models must be equal to one of the allowed values, querystring/models must match a schema in anyOf.

答案1

得分: 1

I think you want an items keyword in there.

const cleanQ = {
  type: "object",
  required: ["models"],
  properties: {
    models: {
      type: "array",
      items: {
        anyOf: [models]
      }
    },
  },
  additionalProperties: false,
};

Having type: array is correct to constrain your data to being an array. However, the subschemas in anyOf require one of the enum values.

To specify what the items of the array need to be, you need to use the items keyword.

英文:

I think you want an items keyword in there.

const cleanQ = {
  type: "object",
  required: ["models"],
  properties: {
    models: {
      type: "array",
      items: {
        anyOf: [models]
      }
    },
  },
  additionalProperties: false,
};

Having type: array is correct to constrain your data to being an array. However the subschemas in anyOf require one of the enum values.

To specify what the items of the array need to be, you need to use the items keyword.

huangapple
  • 本文由 发表于 2023年5月11日 05:12:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定