Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL Blackbox / "Any" type?

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.

like image 574
Jon Cursi Avatar asked Aug 09 '17 19:08

Jon Cursi


2 Answers

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.stringifying 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.

like image 137
Jon Cursi Avatar answered Sep 17 '22 03:09

Jon Cursi


@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! } 
like image 40
a paid nerd Avatar answered Sep 21 '22 03:09

a paid nerd