How to execute GraphQL query from server

I use graphql-express to create an endpoint where I can execute graphql queries. Although I use Sequelize with an SQL database, it is embarrassing to use it directly from the server outside of my graphql functions resolve. How do I access my graphql API from the same server as in it?

This is how I set the 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, I want to be able to do something like this:

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

How do I create this function query?

+4
source share
2 answers

GraphQL.js http-. express-graphql - http.

graphql, , .

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

:

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);
})
+5

@aᴍɪʀ, / :

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)

, " ' .

0

Source: https://habr.com/ru/post/1665511/


All Articles