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

查看:244
本文介绍了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从不具有相同的结构,有时对于获得颜色没有用处,例如sakes。在mongoose中,可以将类型定义为:

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:


editOptions:{}

editOptions : {}

这些editOptions通常对每个框都是唯一的。有些属性是共享的,但大多数都是唯一的。

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 ,只需实现它:

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天全站免登陆