【发布时间】:2019-06-23 01:38:50
【问题描述】:
我正在设置一个 nodeJS GraphQL API,并且我正在试验关于我的一种资源输出类型的阻塞点。
该功能是一个包含三个不同级别的表单:
- 1 级 - 表单模板
- 2 级 - formItems(templateId、类型(视频、图像、问题) - 与 formTemplate 的 1-N 关系)
- 3 级 - formQuestions(当且仅当 formItems.type 为“问题”时,与 formItem 的关系为 0-1)
我的 GraphQL 资源正在返回数据库中的所有模板,因此它是一个数组,每个模板都返回他的所有项目,并且每个“问题”类型的项目都需要返回一个包含相关问题的数组。
我的问题是:我真的不知道如何为类型不同于“问题”的 formItems 返回一个空对象类型,或者对于这种情况是否有更好的方法
我尝试查看 GraphQL 指令和内联片段,但我认为它确实需要由后端管理,因为它对 API 使用者是透明的。
const formTemplate = new GraphQLObjectType({
name: 'FormTemplate',
fields: () => {
return {
id: {
type: new GraphQLNonNull(GraphQLInt)
},
authorId: {
type: new GraphQLNonNull(GraphQLInt)
},
name: {
type: new GraphQLNonNull(GraphQLString)
},
items: {
type: new GraphQLList(formItem),
resolve: parent => FormItem.findAllByTemplateId(parent.id)
}
}
}
})
const formItem = new GraphQLObjectType({
name: 'FormItem',
fields: () => {
return {
id: {
type: new GraphQLNonNull(GraphQLInt)
},
templateId: {
type: new GraphQLNonNull(GraphQLInt)
},
type: {
type: new GraphQLNonNull(GraphQLString)
},
question: {
type: formQuestion,
resolve: async parent => FormQuestion.findByItemId(parent.id)
}
}
}
})
const formQuestion= new GraphQLObjectType({
name: 'FormQuestion',
fields: () => {
return {
id: {
type: new GraphQLNonNull(GraphQLInt)
},
itemId: {
type: new GraphQLNonNull(GraphQLInt)
},
type: {
type: new GraphQLNonNull(GraphQLString)
},
label: {
type: new GraphQLNonNull(GraphQLString)
}
}
}
})
我的 GraphQL 请求:
query {
getFormTemplates {
name
items {
type
question {
label
type
}
}
}
}
我的期望是
{
"data": {
"getFormTemplates": [
{
"name": "Form 1",
"items": [
{
"type": "question",
"question": {
"label": "Question 1",
"type": "shortText"
},
{
"type": "rawContent"
"question": {}
}
]
}
]
}
}
【问题讨论】:
-
为什么不使用普通的 dataType 而不是新的 GrapgQLNonNull。 ex - authorId: {type: GraphQLInt}
标签: node.js graphql graphql-js