Aar*_*ver 5 node.js express lodash graphql graphiql
第一次尝试 GraphQL,我希望一个架构类型能够访问另一个架构类型中的对象数组。在将其连接到 MongoDB 之前,我使用本地数据和 lodash 来测试它。关于我的尝试,我遇到了一些错误。我知道我已经很接近了。任何援助将不胜感激。
以下是我的最新尝试。我使用 express-graphql 访问 GraphQLList 并使用 GraphQLID 访问第二个架构。
架构.js
var projects = [
{
name: "Title 1",
subtitle: "Subtitle 1",
summary: "Lorem ipsum....",
languageId: ["4", "2"],
id: "1"
},
...
var languages = [
{ name: "Javascript", id: "1" },
{ name: "HTML", id: "2" },
{ name: "CSS", id: "3" },
{ name: "Python", id: "4" },
]
...
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
subtitle: { type: GraphQLString },
summary: { type: GraphQLString },
languages: {
type: new GraphQLList(GraphQLID),
resolve(parent, args) {
console.log(parent)
return _.find(languages, { id: parent.languageId })
}
}
})
});
const LanguageType = new GraphQLObjectType({
name: 'Language',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
})
});
//Root Queries
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
project: {
type: ProjectType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return _.find(projects, { id: args.id });
}
},
language: {
type: LanguageType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return _.find(languages, { id: args.id })
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
目的是在 Graphiql 中显示该项目中使用的语言列表,看起来像这样......
{
"data": {
"project": {
"name": "Project 1"
languages{
names{
"Python"
"HTML"
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
相反,我得到以下内容......
{
"errors": [
{
"message": "Syntax Error: Expected Name, found }",
"locations": [
{
"line": 7,
"column": 7
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我重新格式化了对一系列语言进行硬编码的决心,这可行,但不起作用。任何建议将不胜感激。感谢大家抽出宝贵的时间。
我不确定您想提出什么查询。但为了返回Languages嵌套在 中Projects,您应该更改字段的返回类型languages。
就像是:
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
subtitle: {type: GraphQLString},
summary: {type: GraphQLString},
languages: {
// change this type to LanguageType
type: new GraphQLList(LanguageType),
resolve(parent, args) {
// No need to lodash here
return languages.filter((language) => {
return parent.languageId.includes(language.id)
})
}
}
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9362 次 |
| 最近记录: |