Strapi-如何使用自定义属性扩展graphql类型模式?
假设我在创建为Strapi内容类型的作者类型架构上有“firstName”和“lastName”属性 我可以使用graphql查询它们,但如果我想查询“fullName”属性而不在我的内容类型上添加该字段,该怎么办 由于字段不存在,现在它显示:无法查询类型为“Author”的字段“fullName”Strapi-如何使用自定义属性扩展graphql类型模式?,graphql,strapi,Graphql,Strapi,假设我在创建为Strapi内容类型的作者类型架构上有“firstName”和“lastName”属性 我可以使用graphql查询它们,但如果我想查询“fullName”属性而不在我的内容类型上添加该字段,该怎么办 由于字段不存在,现在它显示:无法查询类型为“Author”的字段“fullName” 如何使用附加的“virtual”字段扩展现有类型架构?我使用api/author/config文件夹中schema.graphql文件中的以下代码实现了这一点: 关键是在使用不同类型名称(Autho
如何使用附加的“virtual”字段扩展现有类型架构?我使用api/author/config文件夹中schema.graphql文件中的以下代码实现了这一点: 关键是在使用不同类型名称(AuthorOverride)时使用附加字段定义模式,以避免重复类型错误 另外,设置类型:{Author:false},使原始类型不可查询 现在,在我的解析器函数“Author.find”(放置在我的Author.js控制器中)中,我可以映射fullName值
如果有人有一个更适合在Strapi中扩展graphql模式的解决方案,请随意发布。刚刚找到了这篇文章,也找到了合适的解决方案。这演示了如何使用带有自定义控制器方法和自定义GraphQL模式的服务函数来获取所需内容。我只是在我自己的项目中实现了同样的功能 您的案例不需要服务功能。您只需要做两件事:
/api/authors/config/schema.graphql.js
中定义fullName
属性,如下所示:Author
的find
和findOne
控制器方法,如下所示:fullName
,还告诉GraphQL在其模式中包括fullName
,以便find
和findOne
可以将其正确地传递给GraphQL
我希望这能有所帮助,因为我觉得在学习了这一点之后,我的水平提高了很多 这是金子!我也觉得在学习了这个之后,我的水平提高了!!!!!!谢谢@wavematt
module.exports = {
definition: `type AuthorOverride {
firstName: String
lastName: String
fullName: String
}`,
query: `
authors: [AuthorOverride]
`,
type: {
Author: false
},
resolver: {
Query: {
authors: {
description: 'Return the authors',
resolver: 'Author.find'
}
}
}
};
module.exports = {
definition:
extend type Author {
fullName: AuthorFullName
}
type AuthorFullName {
firstName: String
lastName: String
}
`,
};
module.exports = {
async find( ctx ) {
let entities;
if ( ctx.query._q ) {
entities = await strapi.services.author.search( ctx.query );
} else {
entities = await strapi.services.author.find( ctx.query );
}
// Add computed field `fullName` to entities.
entities.map( entity => {
entity.fullName = `${entity.firstName} ${entity.lastName}`;
return entity;
} );
return entities.map( entity => sanitizeEntity( entity, { model: strapi.models.author } ) );
},
async findOne( ctx ) {
const { id } = ctx.params;
let entity = await strapi.services.author.findOne( { id } );
if ( ! entity ) {
return ctx.notFound();
}
// Add computed field `fullName` to entity.
entity.fullName = `${entity.firstName} ${entity.lastName}`;
return sanitizeEntity( entity, { model: strapi.models.author } );
},
};