GraphQL - Get all fields from nested JSON object

后端 未结 2 1710
囚心锁ツ
囚心锁ツ 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:20

    I can do the second version, but it requires lots of extra code, including creating a NestedObjectType and specifying all the nested properties.

    Do it! It will be great. That's the way to go in order to use GraphQL to its full potential.

    Aside from preventing over-fetching, it also gives you a lot of other benefits like type validation, and more readable and maintainable code since your schema gives a fuller description of your data. You'll thank yourself later for doing the extra work up front.

    If for some reason you really don't want to go that route though and fully understand the consequences, you could encode the nested objects as strings using JSON.stringify.

    But like I said, I recommend you don't!

    0 讨论(0)
  • 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");
    
    
    0 讨论(0)
提交回复
热议问题