How to execute GraphQL query from server

前端 未结 2 564
温柔的废话
温柔的废话 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);
    })
    
    0 讨论(0)
  • 2021-02-07 14:13

    I would like to complete the answer from @aᴍɪʀ by providing the pattern for properly doing a query / mutation with parameters:

    const params = {
      username: 'john',
      password: 'hello, world!',
      userData: {
        ...
      }
    }
    
    query(`mutation createUser(
              $username: String!,
              $password: String!,
              $userData: UserInput) {
      createUserWithPassword(
        username: $username,
        password: $password,
        userData: $userData) {
        id
        name {
          familyName
          givenName
        }
      }
    }`, params)
    

    This way, you don't have to deal with the string construction bits " or ' here and there.

    0 讨论(0)
提交回复
热议问题