Dynamic field in graphql object type

2019-07-18 03:55发布

问题:

I have some GraphQL types:

const Atype = new GraphQLObjectType({
  name: 'Atype',
  fields: {
    data: { type: ADataType },
    error: { type: GraphQLString },
  }
})

and

const Btype = new GraphQLObjectType({
  name: 'Btype',
  fields: {
    data: { type: BDataType },
    error: { type: GraphQLString },
  }
})

It looks redundant because only data fields are different...

How can I solve it in more elegant way in GraphQL ?

回答1:

I created a new Type named Mixed just to solve similar issue., Mixed works as mongoose Mixed type, If you're familiar with it.

Create a new file named GraphQLMixed.js or name it whatever you want and place this code inside it.

import { GraphQLScalarType } from 'graphql';

const GraphQLMixed = new GraphQLScalarType({
  name: 'Mixed',
  serialize: value => value,
  parseValue: value => value,
  parseLiteral: ast => ast.value
});

export default GraphQLMixed;

Now, Based on your syntax I assume you're using express-graphql, So wherever you want to use this type, Do this

const GraphQLMixed = require('path/to/file/GraphQLMixed');

const Atype = new GraphQLObjectType({
  name: 'Atype',
  fields: {
    data: { type: GraphQLMixed },
    error: { type: GraphQLString },
  }
})

const Btype = new GraphQLObjectType({
  name: 'Btype',
  fields: {
    data: { type: GraphQLMixed },
    error: { type: GraphQLString },
  }
})

Hope this works and helps.