有没有一种方法可以获取 Strapi CMS 内容类型的结构?

6

一个 "产品" 的内容类型,具有以下字段:

  • 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中不行,那么其他无头CMS(如Hasura和Sanity)是否可以实现?

2个回答

3

您需要使用模型(Models),该链接中有相关介绍:
链接失效 -> 新链接

模型是数据库结构的一种表示方式,由两个分离的文件组成:一个包含模型选项(例如:生命周期钩子)的JavaScript文件和一个代表存储在数据库中的数据结构的JSON文件。

这正是您所需要的。
我通过添加自定义端点来获取此信息 - 您可以在此处查看我如何实现 - https://stackoverflow.com/a/63283807/5064324https://dev59.com/7Lvpa4cB1Zd3GeqPAOPl#62634233.

对于处理程序,您可以采取以下操作:

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
} 

欢迎评论和提问


1

这个答案指引了我正确的方向,但是在 strapi 4.4.3 版本中,strapi.models 对我来说是未定义的。

对我有效的是以下的控制器:

async getFields(ctx) {
    const model = strapi.db.config.models.find( model => model.collectionName === 'clients' );
    return model.attributes;
  },

clients替换为您内容类型的复数名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接