简体   繁体   中英

GraphQL How to define a new type dynamically

How could I dynamically create a type, eg:

const schema = gql`
    type Human {
      humanoid: Humanoid
      typeOfHumanoid: 'assign a value from Humanoid.id'
    }
    type 'assign a value from Humanoid.id' {
       name
       height
    }
    type Humanoid {
       id
    }
    type Query {
       human: Human
    }`;


query = `query{
    human{
       // a value for example "Humanoid-id-sh@q" 
       typeOfHumanoid{{
         humaniod.id{
            name
            height
          }
        }
        humanoid{
         id
        }
        }
    }
}`
result = `human {
         humanoind{
           "Humanoid-id-sh@q"
         }
         "Humanoid-id-sh@q"{
           "your name"
           "your height"
         }
         }`

When I build the schema I don't want to name the type until I fetch humanoid.id from APIs.

the answer is to define a custom scalar type using

const { GraphQLScalarType } = require("graphql");
const JsonForamt = GraphQLScalarType({
    name: "Json",
    description: "",
    parseValue: (value) =>{
        // write your validation logic here
    },
    serialize: (value) => {
        // write your logic here
    }
});

then you define your custom scalar in your schema

gql`
    scalar Json
    type Human {
        human: Json
    }
`;

here's a documentation from apollo Apollo Custom Scalar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM