Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.JS graphql get requested fields

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.

like image 511
Ákos Vandra-Meyer Avatar asked May 23 '26 17:05

Ákos Vandra-Meyer


1 Answers

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.

@jenyus-org/graphql-utils

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

graphql-fields-list

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 };
}

Other similar libs

https://www.npmjs.com/package/graphql-parse-resolve-info https://github.com/robrichard/graphql-fields

like image 59
Timofey Yatsenko Avatar answered May 26 '26 16:05

Timofey Yatsenko