GraphQL - Get all fields from nested JSON object

后端 未结 2 1711
囚心锁ツ
囚心锁ツ 2021-02-05 13:47

I\'m putting a GraphQL wrapper over an exiting REST API as described in Zero to GraphQL in 30 minutes. I\'ve got an API endpoint for a product with one property that points to a

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 14:40

    You may try to use scalar JSON type. You can find more here (based on apollographql).

    • add scalar JSON to a schema definition;
    • add {JSON: GraphQLJSON} to a resolve functions;
    • use JSON type in a shema:
    
        scalar JSON
        type Query {
            getObject: JSON
        }
    
    
    • an example of a query:
    
        query {
          getObject
        }
    
    
    • a result:
    
        {
          "data": {
            "getObject": {
              "key1": "value1",
              "key2": "value2",
              "key3": "value3"
            }
          }
        }
    
    

    Basic code:

    
        const express = require("express");
        const graphqlHTTP = require("express-graphql");
        const { buildSchema } = require("graphql");
        const GraphQLJSON = require("graphql-type-json");
    
        const schema = buildSchema(`
          scalar JSON
    
          type Query {
            getObject: JSON
          }
        `);
    
        const root = {
          JSON: GraphQLJSON,
    
          getObject: () => {
            return {
              key1: "value1",
              key2: "value2",
              key3: "value3"
            };
          }
        };
    
        const 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");
    
    

提交回复
热议问题