Home > Net >  GraphQL: How to handle a schema with a mix of String and JSON without using grahql-type-json?
GraphQL: How to handle a schema with a mix of String and JSON without using grahql-type-json?

Time:12-13

I am new to GraphQL and still learning. I have a rest API returning response as below:

    {
    "campaign_types": [
        {
            "name": "USA",
            "scenarios": [
                {
                    "id": "jsdx-sdsd-xsds",
                    "name": "NBA"
                },
                {
                    "id": "jsds-sdfs-xdfd",
                    "name": "NFL"
                }
            ],
            "id:": 0
        },
        {
            "name": "Australia",
            "scenarios": [
                {
                    "id": "jtds-sada-xdfs",
                    "name": "AFL"
                },
                {
                    "id": "klhj-sdfs-fdfs",
                    "name": "NRL"
                }
            ],
            "id:": 1
        }
    ]
}

I would like to convert this into a GraphQL API in another application build with TypeScript and React frontend because it handles only GraphQL API. My requirement is in my 2nd application when I make a GraphQL API call it should return the same API response as the rest API.

I am getting this error when I have defined my GraphQL schema as below:

type CommsCampaignType {
    id: ID!
    name: String!
    scenarios: [JSON]
}

Error:

Error: Type "JSON" not found in document

I saw some posts which said of using grahql-type-json but I would like to do it without using that if there is a way. The end result I am looking for is in my UI I have a dropdown which shows Campaign_Type name as "USA", "Australia" and when I select that should show the respective scenario name "NBA", "NFL", and "AFL", "NRL" respectively in a 2nd dropdown. So my GraphQL API query should be able to produce that result.

If anyone could suggest a best method for this, that would be great. Thanks.

CodePudding user response:

Define a Scenario type:

type Scenario {
  id: ID!
  name: String!
}

Then use it in your CommsCampaignType:

type CommsCampaignType {
    id: ID!
    name: String!
    scenarios: [Scenario]
}
  • Related