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