问题描述
具有以下字段的内容类型“产品”:
是否有 API 端点来检索“产品”内容类型的结构或架构而不是获取值?
例如:在端点 localhost:1337/products
上,响应可以是:
[
{
field: "title",type: "string",other: "col-xs-12,col-5"
},{
field: "qty",type: "int"
},{
field: "description",type: "string"
},{
field: "price",type: "double"
}
]
模式或表的结构而不是实际值被发送到哪里?
如果不是在 Strapi CMS 中,是否可以在 Hasura 和 Sanity 等其他无头 CMS 上实现?
解决方法
您需要使用 Models,来自链接:
模型是数据库结构的表示。它们被分成两个单独的文件。包含模型选项(例如:生命周期挂钩)的 JavaScript 文件,以及表示存储在数据库中的数据结构的 JSON 文件。
这正是您所追求的。
我获取此信息的方式是添加自定义端点 - 请在此处查看我的答案以了解如何执行此操作 - https://stackoverflow.com/a/63283807/5064324 & https://stackoverflow.com/a/62634233/5064324。
对于处理程序,您可以执行以下操作:
async getProductModel(ctx) {
return strapi.models['product'].allAttributes;
}
我需要适用于所有内容类型的解决方案,因此我制作了一个带有 /modelStructure/*
端点的插件,您可以在其中提供模型名称,然后传递给处理程序:
//more generic wrapper
async getModel(ctx) {
const { model } = ctx.params;
let data = strapi.models[model].allAttributes;
return data;
},async getProductModel(ctx) {
ctx.params['model'] = "product"
return this.getModel(ctx)
},//define all endpoints you need,like maybe a Page content type
async getPageModel(ctx) {
ctx.params['model'] = "page"
return this.getModel(ctx)
},//finally I ended up writing a `allModels` handler
async getAllModels(ctx) {
Object.keys(strapi.models).forEach(key => {
//iterate through all models
//possibly filter some models
//iterate through all fields
Object.keys(strapi.models[key].allAttributes).forEach(fieldKey => {
//build the response - iterate through models and all their fields
}
}
//return your desired custom response
}
欢迎评论和提问