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
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!
You may try to use scalar JSON type. You can find more here (based on apollographql).
scalar JSON
to a schema definition;{JSON: GraphQLJSON}
to a resolve functions;
scalar JSON
type Query {
getObject: JSON
}
query {
getObject
}
{
"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");