Reputation: 15416
I have a schema type like this:
type Instance {
id: ID!
parentSeries: ID
tags: JSON
}
The tags field is the dynamic JSON type (https://github.com/taion/graphql-type-json). It's also incredibly large. Ideally on the client, I can specify which fields from with tags I return. Is this possible with GraphQL/Apollo? What would you suggest if not?
Upvotes: 0
Views: 3934
Reputation: 936
You could add parameter in your tags
like path or some other kind of filters:
type Instance {
id: ID!
parentSeries: ID
tags(path:String): JSON
}
then implement filter in your resolver like @Daniel Rearden's answer
HOWEVER! Why do you design it with a HUGE json???
Usually I use JSON when there is only a small amount of things and "shape" of data is can't be determined at compile time. or simply server doesn't care the contents of data, the client will do all the work.
In your case, the JSON data is really huge, then I guess breaking it to smaller types would be a better approach
Upvotes: 0
Reputation: 84687
You could include a path
argument on the field and then use something like lodash
's get
to transform the JSON item according to the provided path:
const resolvers = {
Instance: {
tags: (instance, args) => {
return _.get(instance.tags, args.path)
},
},
}
You could apply any number of arbitrary transformations this way to customize the returned JSON object. But, since you're returning a scalar, there is no way to just provide a selection set for the field.
Folks often feel they need to use a JSON scalar simply because the data they are working with is a map. However, a map can easily be transformed into an array, which can easily be represented in your schema without a JSON scalar. So you can just turn this:
{
"foo": {
"propA": "A",
"propA": "B"
},
"bar": {
"propA": "A"
"propA": "B"
}
}
into this:
[
{
"tagName": "foo",
"propA": "A",
"propA": "B"
},
{
"tagName": "bar",
"propA": "A",
"propA": "B"
}
]
Upvotes: 1