简体   繁体   中英

How to include fields in api server and remove it before returning to results to client in Graphql

I have a Node.js GraphQL server. From the client, I am trying get all the user entries using a query like this:

{
    user {
        name
        entries {
            title
            body
        }
    }
}

In the Node.js GraphQL server, however I want to return user entries that are currently valid based on publishDate and expiryDate in the entries object.

For example:

{
    "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"
        }
    ]
}

should return this

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

The entries is fetched via a delegateToSchema call ( https://www.apollographql.com/docs/graphql-tools/schema-delegation.html#delegateToSchema ) and I don't have an option to pass publishDate and expiryDate as query parameters. Essentially, I need to get the results and then filter them in memory.

The issue I face is that the original query doesn't have publishDate and expiryDate in it to support this. Is there a way to add these fields to delegateToSchema call and then remove them while sending them back to the client?

You are looking for transformResult

Implementation details are:

  1. At delegateToSchema you need to define transforms array.
  2. At Transform you need to define transformResult function for filtering results.
  3. If you have ability to send arguments to remote GraphQL server, then you should use transformRequest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM