文档服务 API:与草稿与发布功能配合使用
页面摘要: 使用文档服务 API 的
status参数,可以检索文档的已发布版本或草稿版本、按状态统计文档数量,并在创建或更新文档时直接发布文档。
默认情况下,当启用 草稿与发布(Draft & Publish)功能时,文档服务 API 返回文档的草稿版本。本页说明如何使用 status 参数来:
- 返回文档的已发布版本,
- 按状态统计文档数量,
- 以及在创建或更新文档时直接发布文档。
向文档服务 API 的查询传入 { status: 'draft' } 与不传入任何 status 参数返回的结果相同。
文档服务 API 默认使用 draft,而 REST API 默认使用 published。因此,向 REST API 发送不带 status 参数的 POST 或 PUT 请求会立即发布,这与本页描述的行为相反。
若要依据文档草稿版本与已发布版本的关联关系(从未发布、已修改等)筛选文档,请参阅 文档服务 API:publicationFilter。
使用 findOne() 获取已发布版本 {#find-one}
返回指定文档的已发布版本。
JavaScript
await strapi.documents('api::restaurant.restaurant').findOne({
documentId: 'a1b2c3d4e5f6g7h8i9j0klm',
status: 'published'
});
响应
{
documentId: "a1b2c3d4e5f6g7h8i9j0klm",
name: "Biscotte Restaurant",
publishedAt: "2024-03-14T15:40:45.330Z",
locale: "en", // default locale
// …
}
使用 findFirst() 获取已发布版本 {#find-first}
返回第一个匹配文档的已发布版本。
JavaScript
const document = await strapi.documents("api::restaurant.restaurant").findFirst({
status: 'published',
});
响应
{
documentId: "a1b2c3d4e5f6g7h8i9j0klm",
name: "Biscotte Restaurant",
publishedAt: "2024-03-14T15:40:45.330Z",
locale: "en", // default locale
// …
}
使用 findMany() 获取已发布版本 {#find-many}
返回所有匹配文档的已发布版本。
JavaScript
const documents = await strapi.documents("api::restaurant.restaurant").findMany({
status: 'published'
});
响应
[
{
documentId: "a1b2c3d4e5f6g7h8i9j0klm",
name: "Biscotte Restaurant",
publishedAt: "2024-03-14T15:40:45.330Z",
locale: "en", // default locale
// …
}
// …
]
仅统计草稿或已发布版本 {#count}
使用文档服务 API 统计文档数量 时,若只想统计草稿或已发布版本的文档,可传入相应的 status 参数:
// 统计草稿文档(实际上也会包含已发布文档)
const draftsCount = await strapi.documents("api::restaurant.restaurant").count({
status: 'draft'
});
// 仅统计已发布文档
const publishedCount = await strapi.documents("api::restaurant.restaurant").count({
status: 'published'
});
由于已发布文档必然同时拥有对应的草稿版本,因此已发布文档仍会被计为拥有一个草稿版本。
这意味着,使用 status: 'draft' 参数进行统计时,仍会返回与其他参数匹配的全部文档数量,即使某些文档已经发布、且不再作为「草稿」或「已修改」显示在 Content Manager 中。若只想统计从未发布的草稿,可传入 'never-published' 或 'never-published-document' 等 publicationFilter 值。
创建草稿并发布 {#create}
创建一个新文档并立即发布。
JavaScript
await strapi.documents('api::restaurant.restaurant').create({
data: {
name: "New Restaurant",
},
status: 'published',
})
响应
{
documentId: "d41r46wac4xix5vpba7561at",
name: "New Restaurant",
publishedAt: "2024-03-14T17:29:03.399Z",
locale: "en" // default locale
// …
}
更新草稿并发布 {#update}
更新一个已有文档并立即发布。
JavaScript
await strapi.documents('api::restaurant.restaurant').update({
documentId: 'a1b2c3d4e5f6g7h8i9j0klm',
data: {
name: "Biscotte Restaurant (closed)",
},
status: 'published',
})
响应
{
documentId: "a1b2c3d4e5f6g7h8i9j0klm",
name: "Biscotte Restaurant (closed)",
publishedAt: "2024-03-14T17:29:03.399Z",
locale: "en" // default locale
// …
}