5

Im pretty new graphQL. My requirement is when sending a query, graphQL should return a JSON response as below

{
    user: '$',
    name: 'Josh',
    age: '30'
}

I tried in following way but not achieved the result.

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    user: String!
  }
`);


// JSON
var json = {
    user: '$',
    name: 'Josh',
    age: '30'
};

var root = {
    user: () => {
      return json;
    }
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

Can someone guide where I'm going wrong.

Thanks in advance.

1
  • 3
    In GraphQL you want to create types for all your returned JSON objects. In your case you should not return String for user but probably an object of type User and then define the user type: type User { user: String! name: String! age: String! }. Consider converting age to Int. Commented Oct 11, 2019 at 13:46

1 Answer 1

6

I implemented in the following method:

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
const { GraphQLJSON, GraphQLJSONObject } = require('graphql-type-json');

var schema = buildSchema(`
  scalar JSON
  type Query {
    getObject: JSON
  }
`);

var root = {
    JSON: GraphQLJSON,
    
    getObject: () => {
      return {
        name: "jshua",
        age: "30",
        place: "china",
        gender: "Male"
      }
    }
    
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

See https://github.com/taion/graphql-type-json

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.