[英]GraphQL. How to write resolver
I just started to get into GraphQL. 我才刚刚开始学习GraphQL。 I am using GraphQL.js and express. 我正在使用GraphQL.js并表达。 Right now I am trying to build a simple example using a hardcoded JSON as the data in my javascript file. 现在,我正在尝试使用一个硬编码的JSON作为javascript文件中的数据来构建一个简单的示例。 I then want to use express middleware to listen to HTTP requests via curl or insomnia. 然后,我想使用快速中间件通过curl或失眠监听HTTP请求。 In the middleware I want to extract the query using body-parser. 在中间件中,我想使用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发布查询时
curl -XPOST -H "Content-Type: application/graphql" -d "{product(name: \\"Apfel\\"){name price}}" http://localhost:4000/graphql curl -XPOST -H“内容类型:application / graphql” -d“ {产品(名称:\\” Apfel \\“){名称价格}}”“ http:// localhost:4000 / graphql
I get the response {"data". 我得到响应{“ data”。 {"product": null}}. {“ product”:null}}。 The resolver doesn't get called. 解析器不会被调用。 How can I do this correctly? 如何正确执行此操作?
Can you try this? 你可以试试这个吗?
var resolvers = { product: (args) => { return products[args.name]; }, }; app.post('/graphql', (req, res) => { graphql(schema, req.body, resolvers) .then((result) => { res.send(JSON.stringify(result, null, 2)); }); });
I think this can solve your issue 我认为这可以解决您的问题
I recomend watching FunFunFunction series episode focused on GraphQl: GraphQl Basics 我推荐观看针对GraphQl的FunFunFunction系列剧集: GraphQl基础
All of his episodes are quite interesting (and really fun)... 他的所有剧集都非常有趣(而且非常有趣)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.