GraphQl 中的动态(唯一)对象 [英] Dynamic (Unique) Objects in GraphQl

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

问题描述

我在看 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...}

这是在:

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

让我们说 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:

编辑选项:{}

这些编辑选项通常对每个框都是唯一的.一些属性是共享的,但大多数是独一无二的.

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.

谢谢.

推荐答案

使用GraphQLScalarType,简单的实现如下:

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 },
    // ...
  },
});

这篇关于GraphQl 中的动态(唯一)对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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