我只是在用GraphQL来弄脏我的手。我在跟踪用于石墨for快件-节点反应的YouTube系列。我刚刚设置了一个基本的GraphQL模式,在这里我有一个硬编码的String数组,它是返回的。我想创建一个查询,使用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,它接受事件名并为我提供索引(是整数)。
graphiql结果
查询
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中,而没有深入研究它的规范,但我想它可能也能够处理基于参数的查询。
发布于 2019-01-03 13:59:27
此错误不特定于GraphQL。
Array.findIndex期望传入一个函数作为它的第一个参数。将为数组中的每个元素调用该函数,直到该函数返回一个真实值为止,此时它将返回该元素的索引。args.eventName的值不是一个函数(它是一个字符串),因此您将得到该错误。
要么传递给它一个函数,比如:
const index = _arr.findIndex(value => value === args.eventName)或者只使用Array.indexOf,这可能就是您想要做的:
const index = _arr.indexOf(args.eventName)https://stackoverflow.com/questions/54022149
复制相似问题