'How to execute GraphQL query from server

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 the server outside of my graphql resolve functions. How do I go about querying my graphql API from the same server as it was defined in?

This is how I set up my graphql endpoint:

const express = require('express');
const router = express.Router();
const graphqlHTTP = require('express-graphql');
const gqlOptions = {
   schema: require('./schema')
};
router.use('/', graphqlHTTP(gqlOptions));

modules.exports = router;

Basically what I want is to be able to do something like this:

query(`
  {
    user(id: ${id}) {
      name
    }
  }
`)

How would I create this query function?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent Cantin