0

我想添加一个资产和一个条目。我正在使用一个表单来输入一些数据并在一个 API 调用中上传一张图片。我正在使用 cloudinary 存储图像,但 Contentful-Management 给了我一个 409 状态代码和一个“版本不匹配”错误。

这些是我在下面采取的步骤(如果您看到我忽略的步骤,请添加任何步骤,非常感谢)

#1. Get space by space id
#2. Get environment
#3. Create Entry
#4. Create a new asset
#5. Assign uploaded image as an entry field

' data ' 是我发布帖子所需的所有数据,uploadHref 是指向来自 Cloudinary 的单个图像的链接。

       const postProperty = (data: Partial<Property>, uploadHref: string) => {
            const SPACE_ID = process.env.NEXT_CONTENTFUL_SPACE_ID;
            const client = createClient({
              accessToken: process.env.NEXT_CONTENTFUL_PERSONAL_ACCESS_TOKEN as string,
            });
            // # 1 Get space by space id
            client.getSpace(SPACE_ID).then((space: Space) => {
              // # 2 Get environment
              space.getEnvironment("master").then(async (environment: Environment) => {
                // # 3 Create Entry
                environment
                  .createEntry("propertyListings", {
                    fields: {
                      id: {
                        "en-US": faker.datatype.number(4) + "-" + data.streetAddress,
                      },
                      firstName: {
                        "en-US": data.firstName,
                      },
                      lastName: {
                        "en-US": data.lastName,
                      },
                      email: {
                        "en-US": data.email,
                      },
                      phone: {
                        "en-US": data.phone,
                      },
                      price: {
                        "en-US": data.price,
                      },
                      streetAddress: {
                        "en-US": data.streetAddress,
                      },
                      city: {
                        "en-US": data.city,
                      },
                      state: {
                        "en-US": data.state,
                      },
                      zipcode: {
                        "en-US": data.zipcode,
                      },
                      latitude: {
                        "en-US": Number(data.latitude as number),
                      },
                      longitude: {
                        "en-US": Number(data.longitude as number),
                      },
                      bedrooms: {
                        "en-US": data.bedrooms,
                      },
                      bathrooms: {
                        "en-US": data.bathrooms,
                      },
                      sqft: {
                        "en-US": Number(data.sqft),
                      },
                      carSpaces: {
                        "en-US": data.carSpaces,
                      },
                      type: {
                        "en-US": data.type,
                      },
                      datePosted: {
                        "en-US": data.datePosted,
                      },
                      petFriendly: {
                        "en-US": data.petFriendly,
                      },
                      images: {
                        "en-US": [],
                      },
                    },
                  })
                  .then(entry => {
                    entry.publish();
                    return environment.getEntry(entry.sys.id)
                  })          
                  .then(function (entry: Entry) {
                    // #4 Create a new asset in my Contentful media section
                    environment
                      .createAssetWithId(faker.datatype.number(4).toString(), {
                        fields: {
                          title: {
                            "en-US": data.streetAddress,
                          },
                          file: {
                            "en-US": {
                              contentType: "image/jpeg",
                              fileName: data.streetAddress + ".jpeg",
                              upload: uploadHref,
                            },
                          },
                        },
                      })
                      .then(async (asset) => await asset.processForAllLocales())
                      .then(async (asset) => await asset.publish())
                      .then(function (asset) {
                        // # 5 Assign uploaded image as an entry field
                        entry.fields["images"]["en-US"] = {
                          sys: {
                            id: asset.sys.id, 
                            linkType: "Asset", 
                            type: "Link" 
                          },
                        };
                      
                        return entry.update()
                       })
                      .then(entry => entry.publish())
                    
                      console.log('Entry object value: ', entry)
                      return entry.update()
                  })
                  .catch(err => console.log("Error Message!: ", err))
              });
            });
          };
4

1 回答 1

2

内容丰富的 DevRel 在这里。

如果您遇到VersionMisMatch大多数情况,您不会在创建或更新后重新分配资源。Contentful 的 API 以新的条目版本响应每个写入操作,这样就可以防止覆盖较新的数据。

我重写了您的示例(未经测试),以使用 API 的结果重新分配返回entry的对象。asset

async function createEntryWithAsset() {
    const space = await client.getSpace(SPACE_ID);
    const environment = await space.getEnvironment("master");
    
    /**
     * Entry creation and publish
     */
    let entry = await environment.createEntry("propertyListings", {
        /* ... */
    });
    // reassign `entry` to have the latest version number
    entry = await entry.publish();
    
    /**
     * Asset creation and publish
     */
    let asset = await environment.createAssetWithId(
        faker.datatype.number(4).toString(),
        {
          /* ... */
        }
    );
    // reassign `asset` to have the latest version number
    asset = await asset.processForAllLocales();
    asset = await asset.publish();
    
    /**
     * Update entry with new asset
     */
    entry.fields["images"]["en-US"] = {
        sys: {
          id: asset.sys.id,
          linkType: "Asset",
          type: "Link",
        },
    };
    entry = await entry.update();
    entry = await entry.publish();
}
    
createEntryWithAsset();
于 2021-09-02T09:34:22.740 回答