Is it possible to specify that a field in GraphQL should be a blackbox, similar to how Flow has an "any" type? I have a field in my schema that should be able to accept any arbitrary value, which could be a String, Boolean, Object, Array, etc.
I've come up with a middle-ground solution. Rather than trying to push this complexity onto GraphQL, I'm opting to just use the String
type and JSON.stringify
ing my data before setting it on the field. So everything gets stringified, and later in my application when I need to consume this field, I JSON.parse
the result to get back the desired object/array/boolean/ etc.
@mpen's answer is great, but I opted for a more compact solution:
const { GraphQLScalarType } = require('graphql') const { Kind } = require('graphql/language') const ObjectScalarType = new GraphQLScalarType({ name: 'Object', description: 'Arbitrary object', parseValue: (value) => { return typeof value === 'object' ? value : typeof value === 'string' ? JSON.parse(value) : null }, serialize: (value) => { return typeof value === 'object' ? value : typeof value === 'string' ? JSON.parse(value) : null }, parseLiteral: (ast) => { switch (ast.kind) { case Kind.STRING: return JSON.parse(ast.value) case Kind.OBJECT: throw new Error(`Not sure what to do with OBJECT for ObjectScalarType`) default: return null } } })
Then my resolvers looks like:
{ Object: ObjectScalarType, RootQuery: ... RootMutation: ... }
And my .gql
looks like:
scalar Object type Foo { id: ID! values: Object! }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With