Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
Hoffmann Avatar asked Jan 02 '17 10:01

Hoffmann


People also ask

Can I use GraphQL with SQL Server?

Introduction​ Hasura allows connecting to a SQL Server database and build a GraphQL API based on the database schema.

How do I connect to a GraphQL server?

Run the server and open http://localhost:5000/graphql in the browser. Click play, and this is how the browser window will look. The server can be queried via any GraphQL API client like Postman or in the browser with GraphiQL.


2 Answers

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);
})
like image 53
Aᴍɪʀ Avatar answered Oct 21 '22 10:10

Aᴍɪʀ


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.

like image 43
Vincent Cantin Avatar answered Oct 21 '22 09:10

Vincent Cantin