Generate Graphql schema from json api response

Viewed 1910

I am using Apollo server 2.0 as graphql aggregation layer over my rest apis ( different microservices).

I want to generate graphql schema directly from the api response of microservices instead of manually writing them by hand which could be error prone.

e.g If my api response is

const restApiResponse = {
  "id": 512,
  "personName": "Caribbean T20 2016",
  "personShortName": "caribbean-t20 2016",
  "startDate": "2016-06-29T19:30:00.000Z",
  "endDate": "2016-08-08T18:29:59.000Z",
  "status": 0,
};

Then I want to generate below schema based on the typeName supplied e.g Person -

type Person {
  id: Float
  personName: String
  personShortName: String
  startDate: String
  endDate: String
  status: Float
}
2 Answers

Finally after lots of searches and look up I wrote a script to do that for me -

There are some minor issues with this such as ints are parsed as Floats but thats fine as I can replace them with int if required.

const { composeWithJson } = require('graphql-compose-json');
const { GQC } = require('graphql-compose');
const { printSchema } = require('graphql'); // CommonJS


const restApiResponse = {
    "id": 399,
    "templateId": 115,
    "amount": 100000,
    "amountINR": 100000,
    "amountUSD": 0,
    "currencyCode": "INR",
    "createdAt": "2018-06-07T00:08:28.000Z",
    "createdBy": 36,
};

const GqlType = composeWithJson('Template', restApiResponse);
const PersonGraphQLType = GqlType.getType();

GqlType.addResolver({
    name: 'findById',
    type: GqlType,
    args: {
      id: 'Int!',
    },
    resolve: rp => {
    },
  });

  GQC.rootQuery().addFields({
    person: GqlType.getResolver('findById'),
  });

const schema = GQC.buildSchema();

console.log(printSchema(schema));

It generates output like this -

type Template {
  id: Float
  templateId: Float
  amount: Float
  amountINR: Float
  amountUSD: Float
  currencyCode: String
  createdAt: String
  createdBy: Float
}

This doesn't really answer your question, but I would recommend you NOT do this. GraphQL defines itself as "unapologetically client-driven", which suggests to me that every query you define should be expressly defined as something the client specifically wants. If you only have FLAT data, you don't need GraphQL, and REST is good enough. If you do not, you'll need to carefully craft and specifically nest your data in the way that the client wants, and makes sense to your UI. There is plenty of tooling to make this easier, but I would advise against what you're asking for.

Related