In Nest.js Graphql, is it possible to fetch the required list of fields from a resolver? To determine which joins to executed, and which not to, for example for this db schema:
Employee
id
employer_id
name
Employer
id
name
In case of the following graphql query:
query {
employees {
id
name
employer {
id
}
}
}
It is not necessary to fetch/join the employer data from the database, since the employer id can be accessed from the employee table.
Basically, you can use @Info https://docs.nestjs.com/graphql/resolvers#graphql-argument-decorators decorator from NestJs which is returning an info parameter from regular apollo resolver.
This decorator injects parsed GraphQL query as AST and allows user to create more complex resolvers.
Working with AST is not straightforward and easy because you need to handle all query types by yourself (fragments, aliases, directives and etc) But fortunately, there are some libs on the market that make all heavy lifting under the hood.
https://www.npmjs.com/package/@jenyus-org/graphql-utils
This also has pretty useful Decorators for NestJS:
https://www.npmjs.com/package/@jenyus-org/nestjs-graphql-utils
CODE
@Query(() => [PostObject])
async posts(
@FieldMap() fieldMap: FieldMap,
) {
console.log(fieldMap);
}
OUTPUT
{
"posts": {
"id": {},
"title": {},
"body": {},
"author": {
"id": {},
"username": {},
"firstName": {},
"lastName": {}
},
"comments": {
"id": {},
"body": {},
"author": {
"id": {},
"username": {},
"firstName": {},
"lastName": {}
}
}
}
}
https://www.npmjs.com/package/graphql-fields-list
Example in NestJS:
{
post { # post: [Post]
id
author: {
id
firstName
lastName
}
}
}
import { fieldsList, fieldsMap } from 'graphql-fields-list';
import { Query, Info } from '@nestjs/graphql';
@Query(() => [Post])
async post(
@Info() info,
) {
console.log(fieldsList(info)); // [ 'id', 'firstName', 'lastName' ]
console.log(fieldsMap(info)); // { id: false, firstName: false, lastName: false }
console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };
}
https://www.npmjs.com/package/graphql-parse-resolve-info https://github.com/robrichard/graphql-fields
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With