Reputation: 3349
I am just getting my hands dirty with GraphQL using Express. I am following the Academind YouTube Series for GraphQL-Express-Node-React. I have just setup a basic GraphQL Schema where I have hardcoded Array of Strings which is returned. I want to create a Query which gives me the index of the element from this hardcoded array using 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);
I created a query getEventIndex(eventName: String): Int
which takes in the event name and provides me the index (which is integer)
graphiql
query
query {
getEventIndex(eventName: "Cooking")
}
result
{
"errors": [
{
"message": "Cooking is not a function",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"getEventIndex"
]
}
],
"data": {
"getEventIndex": null
}
}
Why would Cooking
here be considered as a function
and not as an argument in createEvent
mutation?
Of course I am jumping into GraphQL without much deep diving into its Specifications but I guess it might be capable of handling parameter based querying too.
Upvotes: 0
Views: 692
Reputation: 84747
This error is not specific to GraphQL.
Array.findIndex expects a function to be passed in as its first parameter. The function is called for each element in the array until the function returns a truthy value, at which point it returns the index of that element. The value of args.eventName
is not a function (it's a String) so you end up with that error.
Either pass it a function, like:
const index = _arr.findIndex(value => value === args.eventName)
or just use Array.indexOf instead, which is probably what you meant to do:
const index = _arr.indexOf(args.eventName)
Upvotes: 1