如何在api服务器中包含字段并在将结果返回到Graphql中的客户端之前将其删除

问题描述 投票:0回答:1

我有一个Node.js GraphQL服务器。从客户端,我正在尝试使用如下查询获取所有用户条目:

{
    user {
        name
        entries {
            title
            body
        }
    }
}

但是,在Node.js GraphQL服务器中,我想返回条目对象中基于publishDateexpiryDate的当前有效的用户条目。

例如:

{
    "user": "john",
    "entries": [
        { 
          "title": "entry1",
          "body": "body1",
          "publishDate": "2019-02-12",
          "expiryDate": "2019-02-13"
        },
        { 
          "title": "entry2",
          "body": "body2",
          "publishDate": "2019-02-13",
          "expiryDate": "2019-03-01"
        },
        { 
          "title": "entry3",
          "body": "body3",
          "publishDate": "2020-01-01",
          "expiryDate": "2020-01-31"
        }
    ]
}

应该归还这个

{
    "user": "john",
    "entries": [
        { 
          "title": "entry2",
          "body": "body2",
          "publishDate": "2019-02-13",
          "expiryDate": "2019-03-01"
        }
    ]
}

entries是通过delegateToSchema调用(https://www.apollographql.com/docs/graphql-tools/schema-delegation.html#delegateToSchema)获取的,我没有选择将publishDate和expiryDate作为查询参数传递。基本上,我需要获得结果,然后在内存中过滤它们。

我面临的问题是原始查询中没有publishDateexpiryDate来支持这一点。有没有办法将这些字段添加到delegateToSchema调用,然后在将它们发送回客户端时删除它们?

node.js graphql apollo graphql-tools
1个回答
2
投票

您正在寻找transformResult

实施细节是:

  1. delegateToSchema你需要定义transforms数组。
  2. Transform,你需要定义transformResult函数来过滤结果。
  3. 如果您能够向远程GraphQL服务器发送参数,那么您应该使用transformRequest
© www.soinside.com 2019 - 2024. All rights reserved.