graphql - 将多个查询的结果合并到一个数组中

graphql - combining results from multiple queries into one array

我正在使用 graphQL 通过组合查询在多个 mongoDB 集合和 API 中执行搜索。所有查询 return 结果类型

{
  _id: string; 
  name: string; 
  type: string;
}

有什么方法可以将数据展平成一个数组吗?

组合查询示例:

query searchAll {
    books(input: {text: "e"}) {
        _id
        name
        type
    }
    magazines(input: {text: "e"}) {
        _id
        name
        type
    }
}

当前的响应如下:

{"data": {
        "books": [
            {
                "_id": "5a8ac759c25b7235ffdc6888",
                "name": "someBook",
                "type": "book"
            }
        ],
        "magazines": [
            {
                "_id": "5a87005bc25b7235ffdc4bdf",
                "name": "someMagazine-1",
                "type": "magazine"
            },
            {
                "_id": "5a870067c25b7235ffdc4be4",
                "name": "someMagazine-2",
                "type": "client"
            }
        ]
    }
}

期望的响应:

{"data": {
    "results": [
            {
                "_id": "5a8ac759c25b7235ffdc6888",
                "name": "someBook",
                "type": "book"
            },
            {
                "_id": "5a87005bc25b7235ffdc4bdf",
                "name": "someMagazine-1",
                "type": "magazine"
            },
            {
                "_id": "5a870067c25b7235ffdc4be4",
                "name": "someMagazine-2",
                "type": "client"
            }
        ]
    }
}

您想研究使用接口,这是一个(稍微更丰富的)模式定义示例:

interface Searchable {
  id: ID!
  name: String!
}

type Book implements Searchable {
  id: ID!
  name: String!
  author: Author!
  publisher: Publisher!
  isbn: String!
}

type Magazine implements Searchable {
  id: ID!
  name: String!
  publisher: Publisher!
  issn: String!
}

input SearchInput {
  text: String!
}

type Query {
  search(input: SearchInput!): [Searchable!]!
}

查询方式如下:

query searchAll {
  search(input: {text: "e"}) {
    __typename
    id
    name
    ... on Book {
      author
      isbn
    }
    ... on Magazine {
      issn
    }
  }
}

search 的解析器将负责调用所有不同的集合并将结果聚合到一个数组中。比这更深入的是 implementation-specific,但是无论您使用哪种 GraphQL 实现,都应该有使用接口(和联合,它们是相似的)的文档。

__typename 字段告诉您返回对象的具体类型,从而让 front-end 代码执行适当的显示逻辑。