validate-custom-fields-interceptor.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
  2. import { ModuleRef } from '@nestjs/core';
  3. import { GqlExecutionContext } from '@nestjs/graphql';
  4. import { LanguageCode } from '@vendure/common/lib/generated-types';
  5. import { getGraphQlInputName } from '@vendure/common/lib/shared-utils';
  6. import {
  7. GraphQLInputType,
  8. GraphQLList,
  9. GraphQLNonNull,
  10. GraphQLSchema,
  11. OperationDefinitionNode,
  12. TypeNode,
  13. } from 'graphql';
  14. import { REQUEST_CONTEXT_KEY } from '../../common/constants';
  15. import { Injector } from '../../common/injector';
  16. import { ConfigService } from '../../config/config.service';
  17. import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
  18. import { parseContext } from '../common/parse-context';
  19. import { RequestContext } from '../common/request-context';
  20. import { validateCustomFieldValue } from '../common/validate-custom-field-value';
  21. /**
  22. * This interceptor is responsible for enforcing the validation constraints defined for any CustomFields.
  23. * For example, if a custom 'int' field has a "min" value of 0, and a mutation attempts to set its value
  24. * to a negative integer, then that mutation will fail with an error.
  25. */
  26. @Injectable()
  27. export class ValidateCustomFieldsInterceptor implements NestInterceptor {
  28. private readonly inputsWithCustomFields: Set<string>;
  29. constructor(private configService: ConfigService, private moduleRef: ModuleRef) {
  30. this.inputsWithCustomFields = Object.keys(configService.customFields).reduce((inputs, entityName) => {
  31. inputs.add(`Create${entityName}Input`);
  32. inputs.add(`Update${entityName}Input`);
  33. return inputs;
  34. }, new Set<string>());
  35. }
  36. async intercept(context: ExecutionContext, next: CallHandler<any>) {
  37. const parsedContext = parseContext(context);
  38. const injector = new Injector(this.moduleRef);
  39. if (parsedContext.isGraphQL) {
  40. const gqlExecutionContext = GqlExecutionContext.create(context);
  41. const { operation, schema } = parsedContext.info;
  42. const variables = gqlExecutionContext.getArgs();
  43. const ctx: RequestContext = (parsedContext.req as any)[REQUEST_CONTEXT_KEY];
  44. if (operation.operation === 'mutation') {
  45. const inputTypeNames = this.getArgumentMap(operation, schema);
  46. for (const [inputName, typeName] of Object.entries(inputTypeNames)) {
  47. if (this.inputsWithCustomFields.has(typeName)) {
  48. if (variables[inputName]) {
  49. await this.validateInput(
  50. typeName,
  51. ctx.languageCode,
  52. injector,
  53. variables[inputName],
  54. );
  55. }
  56. }
  57. }
  58. }
  59. }
  60. return next.handle();
  61. }
  62. private async validateInput(
  63. typeName: string,
  64. languageCode: LanguageCode,
  65. injector: Injector,
  66. variableValues?: { [key: string]: any },
  67. ) {
  68. if (variableValues) {
  69. const entityName = typeName.replace(/(Create|Update)(.+)Input/, '$2');
  70. const customFieldConfig = this.configService.customFields[entityName as keyof CustomFields];
  71. if (variableValues.customFields) {
  72. await this.validateCustomFieldsObject(
  73. customFieldConfig,
  74. languageCode,
  75. variableValues.customFields,
  76. injector,
  77. );
  78. }
  79. const translations = variableValues.translations;
  80. if (Array.isArray(translations)) {
  81. for (const translation of translations) {
  82. if (translation.customFields) {
  83. await this.validateCustomFieldsObject(
  84. customFieldConfig,
  85. languageCode,
  86. translation.customFields,
  87. injector,
  88. );
  89. }
  90. }
  91. }
  92. }
  93. }
  94. private async validateCustomFieldsObject(
  95. customFieldConfig: CustomFieldConfig[],
  96. languageCode: LanguageCode,
  97. customFieldsObject: { [key: string]: any },
  98. injector: Injector,
  99. ) {
  100. for (const [key, value] of Object.entries(customFieldsObject)) {
  101. const config = customFieldConfig.find(c => getGraphQlInputName(c) === key);
  102. if (config) {
  103. await validateCustomFieldValue(config, value, injector, languageCode);
  104. }
  105. }
  106. }
  107. private getArgumentMap(
  108. operation: OperationDefinitionNode,
  109. schema: GraphQLSchema,
  110. ): { [inputName: string]: string } {
  111. const mutationType = schema.getMutationType();
  112. if (!mutationType) {
  113. return {};
  114. }
  115. const map: { [inputName: string]: string } = {};
  116. for (const selection of operation.selectionSet.selections) {
  117. if (selection.kind === 'Field') {
  118. const name = selection.name.value;
  119. const inputType = mutationType.getFields()[name];
  120. for (const arg of inputType.args) {
  121. map[arg.name] = this.getInputTypeName(arg.type);
  122. }
  123. }
  124. }
  125. return map;
  126. }
  127. private getNamedTypeName(type: TypeNode): string {
  128. if (type.kind === 'NonNullType' || type.kind === 'ListType') {
  129. return this.getNamedTypeName(type.type);
  130. } else {
  131. return type.name.value;
  132. }
  133. }
  134. private getInputTypeName(type: GraphQLInputType): string {
  135. if (type instanceof GraphQLNonNull) {
  136. return this.getInputTypeName(type.ofType);
  137. }
  138. if (type instanceof GraphQLList) {
  139. return this.getInputTypeName(type.ofType);
  140. }
  141. return type.name;
  142. }
  143. }