parse-context.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { ArgumentsHost, ExecutionContext } from '@nestjs/common';
  2. import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
  3. import { Request, Response } from 'express';
  4. import { GraphQLResolveInfo } from 'graphql';
  5. import { InternalServerError } from '../../common/error/errors';
  6. export type RestContext = { req: Request; res: Response; isGraphQL: false; info: undefined };
  7. export type GraphQLContext = {
  8. req: Request;
  9. res: Response;
  10. isGraphQL: true;
  11. info: GraphQLResolveInfo;
  12. };
  13. /**
  14. * Parses in the Nest ExecutionContext of the incoming request, accounting for both
  15. * GraphQL & REST requests.
  16. */
  17. export function parseContext(context: ExecutionContext | ArgumentsHost): RestContext | GraphQLContext {
  18. // TODO: Remove this check once this issue is resolved: https://github.com/nestjs/graphql/pull/1469
  19. if ((context as ExecutionContext).getHandler?.()?.name === '__resolveType') {
  20. return {
  21. req: context.getArgs()[1].req,
  22. res: context.getArgs()[1].res,
  23. isGraphQL: false,
  24. info: undefined,
  25. };
  26. }
  27. if (context.getType() === 'http') {
  28. const httpContext = context.switchToHttp();
  29. return {
  30. isGraphQL: false,
  31. req: httpContext.getRequest(),
  32. res: httpContext.getResponse(),
  33. info: undefined,
  34. };
  35. } else if (context.getType<GqlContextType>() === 'graphql') {
  36. const gqlContext = GqlExecutionContext.create(context as ExecutionContext);
  37. return {
  38. isGraphQL: true,
  39. req: gqlContext.getContext().req,
  40. res: gqlContext.getContext().res,
  41. info: gqlContext.getInfo(),
  42. };
  43. } else {
  44. throw new InternalServerError(`Context "${context.getType()}" is not supported.`);
  45. }
  46. }