【问题标题】:Is there a way to get a structure of a Strapi CMS Content Type?有没有办法获得 Strapi CMS 内容类型的结构?
【发布时间】:2021-05-16 16:30:22
【问题描述】:

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

  • 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"
  }
]

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

如果不在 Strapi CMS 中,这是否可以在 Hasura 和 Sanity 等其他无头 CMS 上实现?

【问题讨论】:

    标签: strapi hasura sanity headless-cms


    【解决方案1】:

    您需要使用Models,来自链接:

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

    这正是您所追求的。
    我获取此信息的方式是添加一个自定义端点 - 在此处查看我的答案以了解如何执行此操作 - https://stackoverflow.com/a/63283807/5064324https://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
    } 
    

    欢迎评论和提问

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 2020-06-18
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2020-02-23
      • 2012-01-02
      相关资源
      最近更新 更多