我想添加一个资产和一个条目。我正在使用一个表单来输入一些数据并在一个 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))
});
});
};