0

Output from a db-query:

    "_id": "5cd532a8452d22435be6a9ac", 
    "properties": {
        "somerandomname": "asd,
        "someotherrandomname": "adsad"
    }

How do I build a graphql type of this?

Something like:

export const aaa = new GraphQLObjectType({
  name: 'aaa',
  fields: () => ({
    _id: {
      type: GraphQLString
    },
    properties: {
      type: GraphQLObjectType 
    },
  })
});

But GraphQLObjectType requires a config.

Any ideas?

Joe
  • 4,692
  • 22
  • 77
  • 135
  • 1
    Possible duplicate of [GraphQL Blackbox / "Any" type?](https://stackoverflow.com/questions/45598812/graphql-blackbox-any-type) – Daniel Rearden May 10 '19 at 11:42

1 Answers1

2

In order to achieve that you would have to define a custom GraphQLScalarType that returns json. You can read more about it in custom-scalars.

Or you could just use the package graphql-type-json that basically is an implementation of a GraphQLScalarType that returns json, something like:

const {GraphQLJSON} = require('graphql-type-json');

const aaa = new GraphQLObjectType({
    name: 'aaa',
    fields: () => ({
        _id: {
            type: GraphQLString
        },
        properties: {
            type: GraphQLJSON
        },
    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        myField: {
            type: aaa,
            resolve(parent, args) {
                // Here: return your object as it is
                // for example:
                return {
                    _id: "this",
                    properties: {
                        somerandomname: "asd",
                        someotherrandomname: "asdad",
                        "what?!": "it also has strings",
                        noway: [
                            "what about them arrays"
                        ]
                    }
                };
            }
        },
    }
})

Then if you query:

{
  myField {
    _id
    properties
  }
}

You will get the output:

{
  "data": {
    "myField": {
      "_id": "this",
      "properties": {
        "somerandomname": "asd",
        "someotherrandomname": "asdad",
        "what?!": "it also has strings",
        "noway": [
          "what about them arrays"
        ]
      }
    }
  }
}
Marco Daniel
  • 3,450
  • 3
  • 24
  • 32