如何在graphql中重用解析器
Posted
技术标签:
【中文标题】如何在graphql中重用解析器【英文标题】:how to reuse resolvers in graphql 【发布时间】:2017-10-03 23:10:33 【问题描述】:我是 graphql 的新手,我正在使用 graphql 创建以下架构
// promotion type
const PromoType = new GraphQLObjectType(
name: 'Promo',
description: 'Promo object',
fields: () => (
id:
type: GraphQLID,
description: 'id of the promo'
,
title:
type: GraphQLString,
description: 'this is just a test'
,
departments:
type: new GraphQLList(DepartmentType),
description: 'departments associated with the promo'
)
)
部门类型
// department type
const DepartmentType = new GraphQLObjectType(
name: 'Department',
description: 'Department object',
fields: () => (
id:
type: GraphQLID,
description: 'id of the department'
,
name:
type: GraphQLString,
description: 'name of the department'
,
createdAt:
type: GraphQLDate,
description: 'date the promo is created'
,
updatedAt:
type: GraphQLDate,
description: 'date the promo is last updated'
)
);
以下是解析器
// Promos resolver
const promos =
type: new GraphQLList(PromoType),
resolve: (_, args, context) =>
let promos = getPromos()
let departments = getDepartmentsById(promos.promoId)
return merge(promos, departments)
;
//Departments resolver
const departments =
type: new GraphQLList(DepartmentType),
args:
promoId:
type: GraphQLID
,
resolve: (_, args, context) =>
return getDepartmentsById(args.promoId)
;
问题是我想使用部门的解析器进入促销的解析器来获取部门。
我可能遗漏了一些明显的东西,但有什么办法可以做到这一点?
【问题讨论】:
【参考方案1】:这是实现它的方法。您想将其视为图形,而不仅仅是单个休息端点。
要获取Promo
的数据,您需要与我在此处的操作类似,但对于父节点,如果这有意义的话。所以,在例如查看者决定您添加查询Promo
。
const PromoType = new GraphQLObjectType(
name: 'Promo',
description: 'Promo object',
fields: () => (
id:
type: GraphQLID,
description: 'id of the promo',
,
title:
type: GraphQLString,
description: 'this is just a test',
,
departments:
type: new GraphQLList(DepartmentType),
description: 'departments associated with the promo',
resolve: (rootValue) =>
return getDepartmentsById(rootValue.promoId);
)
);
【讨论】:
我的意思是我不想为单个字段编写解析器,如果有任何“自动”方法可以做到这一点。我已经使用了 Apollo 工具和服务器。以上是关于如何在graphql中重用解析器的主要内容,如果未能解决你的问题,请参考以下文章
如何在 GraphQL 解析器中添加用于缓存的 redis 客户端
如何使用 scala 在 playframework 2.0 中重用异常解析器