有没有办法获取 Strapi CMS 内容类型的结构?

jun*_*ell 6 strapi sanity hasura headless-cms

内容类型“产品”具有以下字段:

  • string标题
  • int数量
  • string描述
  • double价格

是否有 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"
  }
]
Run Code Online (Sandbox Code Playgroud)

模式或表的结构而不是实际值发送到哪里?

如果不在 Strapi CMS 中,这在其他无头 CMS(例如 Hasura 和 Sanity)上是否可行?

gho*_*osh 3

您需要使用Models,来自链接:
链接已失效 ->新链接

模型是数据库结构的表示。它们被分成两个单独的文件。包含模型选项(例如:生命周期挂钩)的 JavaScript 文件和表示数据库中存储的数据结构的 JSON 文件。

这正是您所追求的。
我获取此信息的方法是添加自定义端点 - 请在此处检查我的答案以了解如何执行此操作 - /sf/answers/4429866521//sf/answers/4384396341/

对于处理程序,您可以执行以下操作:

async getProductModel(ctx) {
  return strapi.models['product'].allAttributes;
}
Run Code Online (Sandbox Code Playgroud)

我需要所有内容类型的解决方案,因此我制作了一个带有/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
} 
Run Code Online (Sandbox Code Playgroud)

欢迎评论和提问