使用 Contentful Management SDK 创建资产时出错

Error while creating asset with Contentful Management SDK

我正在使用内容管理 JS SDK,版本 5.21.1

正在尝试创建新的图像资产但出现错误。我尝试先上传图片并调用 createAsset:

const space = await this.client.getSpace(process.env.CONTENTFUL_SPACE_ID);
const environment = await space.getEnvironment(this.environment);
const upload = await environment.createUpload({ file: bytes });
const asset = await environment.createAsset({
  fields: {
    title: {
      [this.locale]: title
    },
    description: {
      [this.locale]: description
    },
    file: {
      [this.locale]: {
        fileName: fileName,
        contentType: contentType,
        uploadFrom: {
          sys: {
            type: 'Link',
            linkType: 'Upload',
            id: upload.sys.id
          }
        }
      }
    }
  }
});

asset.processForAllLocales();

return await asset.publish();

我也尝试过直接使用 createAssetFromFiles:

const space = await this.client.getSpace(process.env.CONTENTFUL_SPACE_ID);
const environment = await space.getEnvironment(this.environment);
const asset = await environment.createAssetFromFiles({
  fields: {
    title: {
      [this.locale]: title
    },
    description: {
      [this.locale]: description
    },
    file: {
      [this.locale]: {
        fileName: fileName,
        contentType: contentType,
        file: bytes
      }
    }
  }
});

asset.processForAllLocales();

return await asset.publish();

这是我得到的错误(两次调用都一样):

{
  "status": 422,
  "statusText": "Unprocessable Entity",
  "message": "Validation error",
  "details": {
    "errors": [
      {
        "name": "required",
        "path": [
          "fields",
          "file",
          "en-US",
          "url"
        ],
        "details": "The property \"url\" is required here"
      }
    ]
  },
  "request": {
    "url": "assets/01Ft5vBdTHzJPzIVJdBOlE/published",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/vnd.contentful.management.v1+json",
      "X-Contentful-User-Agent": "sdk contentful-management.js/5.21.1; platform node.js/v13.12.0; os macOS/19.4.0;",
      "Authorization": "Bearer ...",
      "user-agent": "node.js/v13.12.0",
      "Accept-Encoding": "gzip",
      "X-Contentful-Version": 1
    },
    "method": "put",
    "payloadData": null
  },
  "requestId": "07778ff81872ddb45d5e1a7266436e22"
}

通过阅读您的文档,我的印象是 URL 是在资产创建后自动创建的,所以我不确定这个错误是什么意思。

非常感谢任何帮助!

所以找到根本原因:

asset.processForAllLocales();

return await asset.publish();

我需要在已处理的资产上调用发布:

const processedAsset = asset.processForAllLocales();

return await processedAsset.publish();

不幸的是,SDK 错误消息含糊不清,文档也很零散。