id-codec-plugin.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { isObject } from '@vendure/common/lib/shared-utils';
  2. import { ApolloServerPlugin, GraphQLRequestListener, GraphQLServiceContext } from 'apollo-server-plugin-base';
  3. import { DocumentNode, OperationDefinitionNode } from 'graphql';
  4. import { GraphqlValueTransformer } from '../common/graphql-value-transformer';
  5. import { IdCodecService } from '../common/id-codec.service';
  6. /**
  7. * Encodes the ids of outgoing responses according to the configured EntityIdStrategy.
  8. *
  9. * This is done here and not via a Nest Interceptor because it's not possible
  10. * according to https://github.com/nestjs/graphql/issues/320
  11. */
  12. export class IdCodecPlugin implements ApolloServerPlugin {
  13. private graphqlValueTransformer: GraphqlValueTransformer;
  14. constructor(private idCodecService: IdCodecService) {}
  15. async serverWillStart(service: GraphQLServiceContext): Promise<void> {
  16. this.graphqlValueTransformer = new GraphqlValueTransformer(service.schema);
  17. }
  18. async requestDidStart(): Promise<GraphQLRequestListener> {
  19. return {
  20. willSendResponse: async requestContext => {
  21. const { document } = requestContext;
  22. if (document) {
  23. const data = requestContext.response.data;
  24. if (data) {
  25. this.encodeIdFields(document, data);
  26. }
  27. }
  28. },
  29. };
  30. }
  31. private encodeIdFields(document: DocumentNode, data: Record<string, any>) {
  32. const typeTree = this.graphqlValueTransformer.getOutputTypeTree(document);
  33. this.graphqlValueTransformer.transformValues(typeTree, data, (value, type) => {
  34. const isIdType = type && type.name === 'ID';
  35. if (type && type.name === 'JSON' && isObject(value)) {
  36. return this.idCodecService.encode(value, [
  37. 'paymentId',
  38. 'fulfillmentId',
  39. 'orderItemIds',
  40. 'orderLineId',
  41. 'promotionId',
  42. 'refundId',
  43. 'groupId',
  44. 'modificationId',
  45. ]);
  46. }
  47. return isIdType ? this.idCodecService.encode(value) : value;
  48. });
  49. }
  50. }