【问题标题】:Simple graphQL query gives error简单的 graphQL 查询给出错误
【发布时间】:2018-04-11 19:22:27
【问题描述】:

我正在尝试将 用于基于 id 的 GET 请求之一。代码如下:

const { graphql, buildSchema } = require('graphql');

EmployeeService.prototype.getEmployee = function() {
  // Construct a schema
  const schema = buildSchema(`
    type Query {
      employee(id="12345") {
        id
        items {
          id
          name
        }
      }
    }
  `);

  // The root provides a resolver function
  let root = {
    employee: () => id
  };

  // Run the GraphQL query
  graphql(schema, '{ employee }', root).then((response) => {
    console.log(response);
  });
};

尝试遵循http://graphql.org/graphql-js/ 上的文档。 我收到 GraphQL 错误:"Syntax Error GraphQL request (3:19) Expected :, found =↵↵2: type Query {↵3: employee (id="12345") {↵ ^↵4: id↵" 请指教。

【问题讨论】:

    标签: graphql angularjs node.js graphql


    【解决方案1】:

    你可能把事情搞混了。架构和解析器是 API 的一部分,不需要在客户端上进行查询。仅出于演示目的,此处提供了一个有效的模式定义(通常在 API 服务器上运行):

    let schema = buildSchema(`
      type Item {
        id: Int!
        name: String!
      }
    
      type Employee {
        id: Int!
        items: [Item]
      }
    
      type Query {
        employee(id: Int!): Employee
      }
    `);
    

    然后您定义您的类型和解析器(简化示例):

    class Employee {
        constructor(id, items) {
            this.id = id;
            this.items = items;
        }
    }
    
    let root = {
        employee: ({id}) => {
            return new Employee(id, [{id: 1, name: 'Item 1'}, {id: 2, name: 'Item2'}]);
        }
    };
    

    然后您可以运行查询:

    const query = `
      {
        employee(id: 1) {
          id,
          items {
            id,
            name
          }
        }
      }
    `;
    
    graphql(schema, query, root).then((response) => {
        console.log(response.data);
    });
    

    要针对远程 API 运行实际查询,请查看 GraphQL clients,例如 Apollolokka

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      相关资源
      最近更新 更多