【发布时间】:2018-09-17 05:16:22
【问题描述】:
我正在尝试使用contentful-management API 在Contentful 中找到创建多个资产的解决方案。
实现单个资产创建的nodeJS脚本是
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;
};
assetObject.js
[
{
link: 'https://example.com/example1.jpg',
title: 'Example 1',
description: 'Description of example 1',
postId: '1234567890',
filename: 'example1.jpeg'
}, ... // Many more
]
这在运行时不会产生错误,也不会做任何事情。我做错了什么?这是我应该使用的方法吗?
【问题讨论】:
-
@xrobert35 有正确的答案,但我要补充一件事:当您处理资产时,您可能希望在发布之前检查
asset.fields.file["en-US"].url是否存在。asset.fields.file["en-US"].url的存在是您将获得的与该区域设置的资产关联的文件的处理已完成的唯一指示。 -
SDK
processForAllLocales函数还有两个选项,如果需要,您可以调整以允许在遇到错误时完成资产处理:options.processingCheckWait和options.processingCheckRetries。详情见contentful.github.io/contentful-management.js/… -
谢谢@CharlieC。感谢您的回复。
标签: javascript node.js contentful contentful-management