【问题标题】:GraphQL. How to write resolverGraphQL。如何编写解析器
【发布时间】:2023-04-08 02:36:01
【问题描述】:

我刚开始接触 GraphQL。我正在使用 GraphQL.js 和 express。现在我正在尝试使用硬编码的 JSON 作为我的 javascript 文件中的数据来构建一个简单的示例。然后我想使用 express 中间件通过 curl 或 insomnia 来监听 HTTP 请求。在中间件中,我想使用 body-parser 提取查询。现在我遇到了解析器的问题。

请看一下我的代码。

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);

这不起作用。当我使用带有

的 curl 发布查询时

curl -XPOST -H "Content-Type: application/graphql" -d "{product(name: \"Apfel\"){name price}}" http://localhost:4000/graphql

我得到响应 {"data". {“产品”:空}}。解析器不会被调用。我怎样才能正确地做到这一点?

【问题讨论】:

    标签: express graphql-js express-graphql


    【解决方案1】:

    你可以试试这个吗?

    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));
        });
    });

    我认为这可以解决您的问题

    【讨论】:

      【解决方案2】:

      我建议观看专注于 GraphQl 的 FunFunFunction 系列剧集: GraphQl Basics

      他所有的剧集都非常有趣(而且非常有趣)......

      【讨论】:

        猜你喜欢
        • 2019-04-03
        • 2019-07-15
        • 2019-07-14
        • 2020-08-19
        • 2021-06-07
        • 1970-01-01
        • 2021-09-10
        • 2020-10-30
        • 2023-04-05
        相关资源
        最近更新 更多