Return only fields requested in GQL query #1339
-
ScopeImproves an existing behavior Compatibility
Feature descriptionThis has already been raised in #292, but the answer and conversation went down the track of schema-based mocking to automatically supply fields values based on their type, rather than limiting the response to the requested fields. However, as @benmonro had asked, I was wondering whether it was possible or whether there was a known way to allow mock resolvers to return a full object graph of the data being fetched, and strip fields in the response data such that only those included in the query are present. For example. If I have a mock resolver which returns all possible data for a given GQL schema type (note that the schema is not known to export const handlers = [
graphql.query('GetUser', (req, res, ctx) => {
return res(ctx.data({
user: {
id: '1',
firstName: 'Jane',
lastName: 'Doe',
address: {
line1: '123 Fake Street',
line2: 'Faketown',
city: 'Fakesville',
state: 'FK'
}
}
})
})
] I could then have a query in my app as follows: query GetUser {
user {
id
firstName
address {
line1
city
}
}
} Ideally, I would like the response from {
"user": {
"id": "1",
"firstName": "Jane",
"address": {
"line1": "123 Fake Street",
"city": "Fakesville"
}
}
} Ideally this would also factor in fragments and directives: query GetUser(
$fullName: Boolean!
$fullAddress: Boolean!
) {
user {
id
firstName
lastName @include(if: $fullName)
address {
...addressFields
}
}
}
fragment addressFields on Address {
line1
line2 @include(if: $fullAddress)
city
state @include(if: $fullAddress)
} Is this something that is on your roadmap, or does anybody know of another library or utility which can take a JSON object and reduce its fields to ones described in a GQL query? Many thanks, and love your work by the way ❤️ |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @kgpax. Thanks for raising this. Filtering out only the requested fields is done by the server, and more specifically, by passing the full resolved payload through the We did, however, provide an example of how you can achieve the fields filtering identical to an actual server: msw/test/graphql-api/compatibility.node.test.ts Lines 19 to 34 in 6c6e119 You can run |
Beta Was this translation helpful? Give feedback.
Hey, @kgpax. Thanks for raising this.
Filtering out only the requested fields is done by the server, and more specifically, by passing the full resolved payload through the
graphql
package, where it also does a few other things like field value validation, directives, etc. This is too much for MSW to ship as default behavior, and even as an opt-in behavior.We did, however, provide an example of how you can achieve the fields filtering identical to an actual server:
msw/test/graphql-api/compatibility.node.test.ts
Lines 19 to 34 in 6c6e119