【问题标题】:Graphql object with random key names具有随机键名的 Graphql 对象
【发布时间】:2019-09-28 07:24:36
【问题描述】:

数据库查询的输出:

    "_id": "5cd532a8452d22435be6a9ac", 
    "properties": {
        "somerandomname": "asd,
        "someotherrandomname": "adsad"
    }

如何构建这个的 graphql 类型?

类似:

export const aaa = new GraphQLObjectType({
  name: 'aaa',
  fields: () => ({
    _id: {
      type: GraphQLString
    },
    properties: {
      type: GraphQLObjectType 
    },
  })
});

但 GraphQLObjectType 需要配置。

有什么想法吗?

【问题讨论】:

标签: graphql


【解决方案1】:

为了实现这一点,您必须定义一个返回 json 的自定义 GraphQLScalarType。您可以在custom-scalars 阅读更多相关信息。

或者你可以只使用包graphql-type-json,它基本上是一个返回json的GraphQLScalarType的实现,类似于:

const {GraphQLJSON} = require('graphql-type-json');

const aaa = new GraphQLObjectType({
    name: 'aaa',
    fields: () => ({
        _id: {
            type: GraphQLString
        },
        properties: {
            type: GraphQLJSON
        },
    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        myField: {
            type: aaa,
            resolve(parent, args) {
                // Here: return your object as it is
                // for example:
                return {
                    _id: "this",
                    properties: {
                        somerandomname: "asd",
                        someotherrandomname: "asdad",
                        "what?!": "it also has strings",
                        noway: [
                            "what about them arrays"
                        ]
                    }
                };
            }
        },
    }
})

那么如果你查询:

{
  myField {
    _id
    properties
  }
}

你会得到输出:

{
  "data": {
    "myField": {
      "_id": "this",
      "properties": {
        "somerandomname": "asd",
        "someotherrandomname": "asdad",
        "what?!": "it also has strings",
        "noway": [
          "what about them arrays"
        ]
      }
    }
  }
}

【讨论】:

  • 我不明白。你能举个例子吗?
  • @Joe,我更新了一个使用包graphql-type-json的示例
  • 谢谢。但我事先不知道房产名称?它总是字符串。属性:{“somestring”:“anotherstring”}
  • 您不必这样做,您只需返回从解析器上的数据库获得的任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2021-11-30
  • 2018-12-23
  • 1970-01-01
  • 2020-09-16
相关资源
最近更新 更多