【发布时间】:2019-01-03 21:59:27
【问题描述】:
我只是在使用 Express 对 GraphQL 进行操作。我正在关注Academind YouTube Series for GraphQL-Express-Node-React。我刚刚设置了一个基本的 GraphQL Schema,我在其中硬编码了返回的字符串数组。我想创建一个查询,它使用 GraphQL (graphiql) 为我提供该硬编码数组中元素的索引
代码
const express = require('express'); // Add Express Module
const bodyParser = require('body-parser'); // Add Body-Parser Middleware for JSON handling in Requests
const graphqlHttp = require('express-graphql'); // Add Middleware for GraphQL Resolvers over Express HTTP
const { buildSchema } = require('graphql'); // Javascript Object-Destructuring (pull objects from packages)
const app = express();
app.use(bodyParser.json()); // JSON parsing Middleware added
app.use('/graphql', graphqlHttp({
schema: buildSchema(`
type RootQuery {
events: [String!]!
getEventIndex(eventName: String): Int
}
type RootMutation {
createEvent(name: String): String
}
schema {
query: RootQuery
mutation: RootMutation
}
`),
rootValue: {
events: () => {
return ['Cooking', 'All-Night Coding', 'Romantic'];
},
getEventIndex: (args) => {
const _arr = ['Cooking', 'All-Night Coding', 'Romantic'];
const index = _arr.findIndex(args.eventName);
return index;
},
createEvent: (args) => {
const eventName = args.name; // same as that of the parameter for `createEvent`
return eventName;
}
},
graphiql: true
}));
app.listen(3000);
我创建了一个查询getEventIndex(eventName: String): Int,它接受事件名称并为我提供索引(整数)
结果为@987654325@
查询
query {
getEventIndex(eventName: "Cooking")
}
结果
{
"errors": [
{
"message": "Cooking is not a function",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"getEventIndex"
]
}
],
"data": {
"getEventIndex": null
}
}
为什么Cooking 在这里被视为function 而不是createEvent 突变中的参数?
当然,我在没有深入了解其规范的情况下直接进入 GraphQL,但我想它也可能能够处理基于参数的查询。
【问题讨论】: