I just started to get into GraphQL. I am using GraphQL.js and express. Right now I am trying to build a simple example using a hardcoded JSON as the data in my javascript file. I then want to use express middleware to listen to HTTP requests via curl or insomnia. In the middleware I want to extract the query using body-parser. Right now I am having trouble with resolvers.
Please have a look at my code.
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema, graphql } = require('graphql');
var bodyParser = require('body-parser');
var schema = buildSchema(`
type Product {
name: String!
price: Int!
}
type Query {
product(name: String): Product
}
`);
var products = {
'Mango': {
name: 'Mango',
price: 12,
},
'Apfel': {
name: 'Apfel',
price: 3,
},
};
resolvers = {
Query: {
product: (root, { name}) => {
return products[name];
},
},
};
var app = express();
app.use(bodyParser.text({ type: 'application/graphql' }));
app.post('/graphql', (req, res) => {
graphql(schema, req.body)
.then((result) => {
res.send(JSON.stringify(result, null, 2));
});
});
app.listen(4000);
This does not work. When I post a query using curl with
curl -XPOST -H "Content-Type: application/graphql" -d "{product(name: \"Apfel\"){name price}}" http://localhost:4000/graphql
I get the response {"data". {"product": null}}. The resolver doesn't get called. How can I do this correctly?