Dynamic field in graphql object type

喜夏-厌秋 提交于 2019-12-24 00:58:08

问题


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.



来源:https://stackoverflow.com/questions/46944891/dynamic-field-in-graphql-object-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!