【发布时间】:2018-06-01 01:07:09
【问题描述】:
我是 GraphQL 的新手,我正在尝试解决我的经理向我提出的问题。
我有以下数据结构可供我使用,通过第 3 方 API(我对其零控制):
[
{
"id": 19,
"date": "2016-10-24T13:59:19",
"date_gmt": "2016-10-24T12:59:19",
"slug: "data",
"provider": {
"name": "data",
"logo": "data",
"destination_url": "data",
"coupon_label": "data",
"coupon_text": "data",
"coupon_code": "data",
"coupon_url": "data",
}
}
]
我需要将其转换为类似于以下查询的 GraphQL 架构:
{
provider(slug: "slug") {
id
date
slug
name
logo
url
coupon {
label
text
code
url
}
}
}
我已经设法使用下面的代码对其中的大部分进行了排序,但是,我不知道如何将优惠券节点组合为一个。
我猜这需要另一种自定义类型?如果是这样,这似乎效率低下,因为优惠券永远不会在提供者类型之外使用,所以我想知道是否有一种我不知道的更“最佳实践”的方式。
import { GraphQLObjectType, GraphQLInt, GraphQLString } from 'graphql'
const ProviderType = new GraphQLObjectType({
name: 'Provider',
fields: () => ({
id: {
type: GraphQLInt,
description: 'The primary key for the provider'
},
slug: {
type: GraphQLString,
description: 'A unique string for the provider'
},
status: {
type: GraphQLString,
description: 'The the published status of the provider'
},
name: {
type: GraphQLString,
description: 'The name of the provider',
resolve (parent) { return parent.provider.name }
},
logo: {
type: GraphQLString,
description: 'The full url of the provider logo',
resolve (parent) { return parent.provider.logo }
},
url: {
type: GraphQLString,
description: 'The full url of the provider',
resolve (parent) { return parent.provider.destination_url }
},
})
})
export default ProviderType
更新:
我已将代码更新为以下内容,但仍然无法正常工作,因此我的假设一定是不正确的(或者我执行不正确)
const ProviderType = new GraphQLObjectType({
name: 'Provider',
fields: () => ({
id: {
type: GraphQLInt,
description: 'The primary key for the provider'
},
slug: {
type: GraphQLString,
description: 'A unique string for the provider'
},
status: {
type: GraphQLString,
description: 'The the published status of the provider'
},
name: {
type: GraphQLString,
description: 'The name of the provider',
resolve (parent) { return parent.provider.name }
},
logo: {
type: GraphQLString,
description: 'The full url of the provider logo',
resolve (parent) { return parent.provider.logo }
},
url: {
type: GraphQLString,
description: 'The full url of the provider',
resolve (parent) { return parent.provider.destination_url }
},
coupon: {
type: CouponType,
description: 'The coupon information for the provider'
}
})
})
const CouponType = new GraphQLObjectType({
name: 'Coupon',
fields: () => ({
label: {
type: GraphQLString,
description: 'The label for the coupon',
resolve (parent) { return parent.provider.coupon_label }
},
text: {
type: GraphQLString,
description: 'The text for the coupon',
resolve (parent) { return parent.provider.coupon_text }
},
code: {
type: GraphQLString,
description: 'The code for the coupon',
resolve (parent) { return parent.provider.coupon_code }
},
url: {
type: GraphQLString,
description: 'The url for the coupon',
resolve (parent) { return parent.provider.coupon_url }
}
})
})
【问题讨论】:
-
您需要在提供商类型的优惠券字段中使用解析器,因为它是嵌套/子字段
标签: javascript graphql graphql-js