graphql对象类型中的动态字段 [英] Dynamic field in graphql object type

查看:529
本文介绍了graphql对象类型中的动态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些GraphQL类型:

I have some GraphQL types:

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

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

它看起来是多余的,因为只有data字段不同...

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

如何在GraphQL中以更优雅的方式解决它?

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

推荐答案

我创建了一个名为 Mixed 的新 Type 以解决类似的问题.类型,如果您熟悉的话.

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

创建一个名为GraphQLMixed.js的新文件,或将其命名为任意名称,并将此代码放入其中.

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;

现在,根据您的语法,我假设您正在使用 express-graphql ,所以无论您想在哪里使用此类型,都请执行此操作

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.

这篇关于graphql对象类型中的动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆