8

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.

1

2 Answers 2

10

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

-1

In your case, I recommend you to use FieldResolver in order to resolve the employer field. You can get more information in resolvers article

#...

@ResolveField()
async employer(@Parent() employee) {
  const { employer_id } = employee;
  return this.employerService.findById(employer_id);
}

#...

2
  • 1
    This is basically a non-answer. The question was about how can one determine the necessity and avoid making this query if the only requested field is the id (which is already present in the Employee table. Jan 21, 2021 at 8:36
  • I understand the point, but it is more convenient for FieldResolver to request all fields to EmployerService.getEmployerById. In that method, the result for the requested employer should be cached. EmployerService.getEmployerById is probably invoked from another part of the system and this is where we will really save execution cost in the database. On the other hand, if you really want to know what fields are requested to the api, you should add this argument decorator "@Info (param ?: string)" And get the list of selected attributes in this property: info.operation.selectionSet Jan 21, 2021 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.