我试图找到一个解决方案,以创建多个资产中
满足的
使用
contentful-management
应用程序编程接口。
节点
实现单个资产创建的脚本是
const client = contentful.createClient({
accessToken: '<content_management_api_key>'
})
client.getSpace('<space_id>')
.then((space) => space.getEnvironment('<environment-id>'))
.then((environment) => environment.createAssetWithId('<asset_id>', {
title: {
'en-US': 'Example 1'
},
file: {
'en-US': {
contentType: 'image/jpeg',
fileName: 'example1.jpeg',
upload: 'https://example.com/example1.jpg'
}
}
}))
.then((asset) => asset.processForAllLocales())
.then((asset) => asset.publish())
.then((asset) => console.log(asset))
.catch(console.error)
它非常简单,易于实现。但是,当想要创建多个资产时,这是行不通的。
在寻找一个有案可稽的方法来实现这一点很多小时后,没有任何结果,我来了
const contentful = require('contentful-management');
const assets = require('./assetObject.js');
async () => {
const client = contentful.createClient({
accessToken: '<content_management_api_key>'
});
const space = await client.getSpace('<space_id>');
const environment = await space.getEnvironment('<environment-id>');
const createdAssets = await Promise.all(
assets.map(
asset =>
new Promise(async () => {
let cmsAsset;
try {
cmsAsset = await environment.createAssetWithId(asset.postId, {
fields: {
title: {
'en-US': asset.title
},
description: {
'en-US': asset.description
},
file: {
'en-US': {
contentType: 'image/jpeg',
fileName: asset.filename,
upload: asset.link
}
}
}
});
} catch (e) {
throw Error(e);
}
try {
await cmsAsset.processForAllLocales();
} catch (e) {
throw Error(e);
}
try {
await cmsAsset.publish();
} catch (e) {
throw Error(e);
}
})
)
);
return createdAssets;
};
资产对象.js
[
{
link: 'https://example.com/example1.jpg',
title: 'Example 1',
description: 'Description of example 1',
postId: '1234567890',
filename: 'example1.jpeg'
}, ... // Many more
]
这在运行时不会产生错误,也不会产生任何作用。我做错了什么?这是我应该用的方法吗?