【问题标题】:customize json response in graphQL在 graphQL 中自定义 json 响应
【发布时间】:2018-07-28 18:41:04
【问题描述】:

我使用 Express-js 和 express graphQL 模块来创建我的端点和网络服务;

我正在寻找在 graphQL 中创建自定义响应的方法,我的端点很简单

从数据库中选择书籍我的回答是

{
  "data": {
    "books": [
      {
        "id": "5b5c02beab8dc1182b2e0a03",
        "name": "dasta"
      },
      {
        "id": "5b5c02c0ab8dc1182b2e0a04",
        "name": "dasta"
      }
    ]
  }
}

但需要这样的东西

{
  "result": "success",
  "msg" : "list ...",
  "data": [
      {
        "id": "5b5c02beab8dc1182b2e0a03",
        "name": "dasta"
      },
      {
        "id": "5b5c02c0ab8dc1182b2e0a04",
        "name": "dasta"
      }
  ]
}

这是我的 bookType

const BookType = new GraphQLObjectType({
    name: 'Book',
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        genre: {type: GraphQLString},
        author_id: {type: GraphQLString},
        author: {
            type: AuthorType,
            resolve(parent, args) {
                return Author.findById(parent.author_id);
            }
        }
    })
});

【问题讨论】:

    标签: node.js express graphql


    【解决方案1】:

    这不是合法的 GraphQL 响应。根据section 7.1 of the spec,在描述了dataerrorsextensions之后:顶级键:

    ...顶级响应映射不得包含上述三个以外的任何条目。

    您可以将这些数据放入extensions;或使其成为 GraphQL API 的显式部分;或者干脆让“成功”被一个结果的存在和没有一个错误所暗示。

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 2017-03-24
      • 2019-02-07
      • 1970-01-01
      • 2020-11-09
      • 2016-12-25
      相关资源
      最近更新 更多