Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Graphql schema from json api response

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
}
like image 891
WitVault Avatar asked Oct 17 '22 10:10

WitVault


1 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
}
like image 177
WitVault Avatar answered Oct 21 '22 02:10

WitVault