简单的graphQL查询会产生错误

时间:2017-11-17 20:32:50

标签: angularjs node.js graphql

我正在尝试根据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↵" 请指教。

1 个答案:

答案 0 :(得分: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 clientsApollolokka等{{3}}