How to execute GraphQL query from server

前端 未结 2 565
温柔的废话
温柔的废话 2021-02-07 13:06

I am using graphql-express to create an endpoint where I can execute graphql queries in. Although I am using Sequelize with a SQL database it feels wrong to use it directly from

2条回答
  •  灰色年华
    2021-02-07 13:57

    GraphQL.js itself does not require a http server to run. express-graphql is just a helper to mount the query resolver to a http endpoint.

    You can pass your schema and the query to graphql, it'll return a Promise that'll resolve the query to the data.

    graphql(schema, query).then(result => {
      console.log(result);
    });
    

    So:

    const {graphql} = require('graphql');
    const schema = require('./schema');
    function query (str) {
      return graphql(schema, str);
    }
    
    query(`
      {
        user(id: ${id}) {
          name
        }
      }
    `).then(data => {
      console.log(data);
    })
    

提交回复
热议问题