Extensions

Warning This chapter applies only to the code first approach.

Extensions is an advanced, low-level feature that lets you define arbitrary data in the types configuration. Attaching custom metadata to certain fields allows you to create more sophisticated, generic solutions. For example, with extensions, you can define field-level roles required to access particular fields. Such roles can be reflected at runtime to determine whether the caller has sufficient permissions to retrieve a specific field.

Adding custom metadata

To attach custom metadata for a field, use the @Extensions() decorator exported from the @nestjs/graphql package.

  1. @Field()
  2. @Extensions({ role: Role.ADMIN })
  3. password: string;

In the example above, we assigned the role metadata property the value of Role.ADMIN. Role is a simple TypeScript enum that groups all the user roles available in our system.

Note, in addition to setting metadata on fields, you can use the @Extensions() decorator at the class level and method level (e.g., on the query handler).

Using custom metadata

The logic that leverages the custom metatada can be as complex as needed. For example, you can create a simple interceptor that stores/logs events per method invocation, or create a sophisticated guard that analyzes requested fields, iterates through the GraphQLObjectType definition, and matches the roles required to retrieve specific fields with the caller permissions (field-level permissions system).

Let’s define a FieldRolesGuard that implements a basic version of such a field-level permissions system.

  1. import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
  2. import { GqlExecutionContext } from '@nestjs/graphql';
  3. import { GraphQLNonNull, GraphQLObjectType, GraphQLResolveInfo } from 'graphql';
  4. import * as graphqlFields from 'graphql-fields';
  5. @Injectable()
  6. export class FieldRolesGuard implements CanActivate {
  7. canActivate(context: ExecutionContext): boolean {
  8. const info = GqlExecutionContext.create(context).getInfo<
  9. GraphQLResolveInfo
  10. >();
  11. const returnType = (info.returnType instanceof GraphQLNonNull
  12. ? info.returnType.ofType
  13. : info.returnType) as GraphQLObjectType;
  14. const fields = returnType.getFields();
  15. const requestedFields = graphqlFields(info);
  16. Object.entries(fields)
  17. .filter(([key]) => key in requestedFields)
  18. .map(([_, field]) => field)
  19. .filter((field) => field.extensions && field.extensions.role)
  20. .forEach((field) => {
  21. // match user and field roles here
  22. console.log(field.extensions.role);
  23. });
  24. return true;
  25. }
  26. }

Warning For illustration purposes, we assumed that every resolver returns either the GraphQLObjectType or GraphQLNonNull that wraps the object type. In a real-world application, you should cover other cases (scalars, etc.). Note that using this particular implementation can lead to unexpected errors (e.g., missing getFields() method).

In the example above, we’ve used the graphql-fields package that turns the GraphQLResolveInfo object into an object that consists of the requested fields. We used this specific library to make the presented example somewhat simpler.

With this guard in place, if the return type of any resolver contains a field annotated with the @Extensions({ role: Role.ADMIN }}) decorator, this role (Role.ADMIN) will be logged in the console if requested in the GraphQL query.