Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic (Unique) Objects in GraphQl

I'm looking at graphql. Is it possible to define an object with arbitrary attributes? Let's say I have some data like:

editOptions : { boxes : 3 , size : { width: 23,height:32} , color: #434343 }, etc...}

and this is in:

{ ... , box : { editOptions : {...} }, ... }

Let's say that editOptions is never with the same structure, sometimes not be useful to have the color, just for example sakes. In mongoose one can just define the type to something like:

editOptions : {}

These editOptions are usually unique for each box. With some attributes being shared but most being unique.

So my question is, is there a way to do this? or is this bad practice and I should change my models.

Thank you.

like image 472
Diogo Barroso Avatar asked Nov 20 '15 05:11

Diogo Barroso


People also ask

What is the GraphQL type for unique ID?

In Dgraph, every node has a unique 64-bit identifier that you can expose in GraphQL using the ID type. An ID is auto-generated, immutable and never reused. Each type can have at most one ID field.

What are the three types of operations in GraphQL?

There are three types of operations that GraphQL models: query – a read‐only fetch. mutation – a write followed by a fetch. subscription – a long‐lived request that fetches data in response to source events.

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).

What makes queries more dynamic and flexible?

Using variables​ In order to make a query re-usable, it can be made dynamic by using variables.


1 Answers

Use GraphQLScalarType, simply implement it like:

import { GraphQLScalarType } from 'graphql/type';
import { GraphQLError } from 'graphql/error';
import { Kind } from 'graphql/language';

const ObjectType = new GraphQLScalarType({
  name: 'ObjectType',
  serialize: value => value,
  parseValue: value => value,
  parseLiteral: (ast) => {
    if (ast.kind !== Kind.OBJECT) {
      throw new GraphQLError(
        `Query error: Can only parse object but got a: ${ast.kind}`, 
        [ast],
      );
    }
    return ast.value;
  },
});

const ReturnType = new GraphQLObjectType({
  name: 'ReturnType',
  fields: {
    // ...
    editOptions: { type: ObjectType },
    // ...
  },
});
like image 102
sofish Avatar answered Oct 05 '22 02:10

sofish