How to return a json string as response in GraphQL

Viewed 10497

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 Answers

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

Related