如何在 Sanity 中验证上传图像的尺寸?

cor*_*ard 5 validation sanity

我在 Sanity 中有一个image类型字段(文档,我需要确保尺寸在特定范围内,以避免破坏他们正在运行的网站。Sanity 提供了验证,但是图像类型只有 \xe2\x80\x9crequired\xe2\x80\x9d 和 \xe2\x80\x9ccustom\xe2\x80\x9d 规则,而传入自定义验证器的字段信息没有包括图像元数据。

\n\n

如何解决此限制并提供 CMS 内维度验证?

\n

cor*_*ard 10

虽然 Sanity 不会将图像元数据传递到验证器中,但您可以从提供的资产 ID 中提取图像格式和尺寸信息。根据此文档,这是一种受支持的、稳定的访问此信息的方式,无需从 Sanity 加载图像对象。

例如,这是传递给Rule.custom验证器的第一个参数:

{
  "_type": "image",
  "alt": "Example Image",
  "asset": {
    "_ref": "image-bff149a0b87f5b0e00d9dd364e9ddaa0-700x650-jpg",
    "_type": "reference"
  }
}
Run Code Online (Sandbox Code Playgroud)

获取图像尺寸可以这样完成:

{
  title: "My Image",
  name: "image",
  type: "image",
  options: {
    accept: "image/*",
  },
  validation: Rule => Rule.custom(image => {
    if (!image) return true
    const { dimensions } = decodeAssetId(image.asset._ref)
    return dimensions.width >= 500 || "Image must be wider"
  }
}

const pattern = /^image-([a-f\d]+)-(\d+x\d+)-(\w+)$/

const decodeAssetId = id => {
  const [, assetId, dimensions, format] = pattern.exec(id)
  const [width, height] = dimensions.split("x").map(v => parseInt(v, 10))

  return {
    assetId,
    dimensions: { width, height },
    format,
  }
}
Run Code Online (Sandbox Code Playgroud)

我还将此功能整合到了sanity-pills库中,这样可以更轻松地执行以下操作:

import { createImageField } from "sanity-pills"

createImageField({
  name: "image",
  validations: {
    required: true,
    minWidth: 500,
    maxHeight: 9000
  },
})
Run Code Online (Sandbox Code Playgroud)