Skip to content

Commit 65722de

Browse files
committed
refactor: regex can be used only for fields with String type
1 parent 0e7a273 commit 65722de

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

src/resolvers/helpers/filterOperators.ts

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
GraphQLInputObjectType,
77
GraphQLScalarType,
88
GraphQLEnumType,
9+
GraphQLString,
910
} from 'graphql-compose/lib/graphql';
1011
import type { Model, Schema, SchemaType, VirtualType } from 'mongoose';
1112
import type { InputTypeComposer } from 'graphql-compose';
@@ -79,35 +80,32 @@ export function _availableOperatorsFields(
7980
: Object.values(availableOperators);
8081

8182
operators.forEach((operatorName: string) => {
82-
const fc = itc.getFieldConfig(fieldName);
8383
// unwrap from GraphQLNonNull and GraphQLList, if present
84-
let fieldType: GraphQLInputType | InputTypeComposer | string = getNamedType(
85-
fc.type
84+
let fieldType: GraphQLInputType | string = getNamedType(
85+
itc.getFieldType(fieldName)
8686
) as GraphQLInputType;
8787

8888
// just treat enums as strings
89-
if (getNamedType(fc.type) instanceof GraphQLEnumType) {
89+
if (fieldType instanceof GraphQLEnumType) {
9090
fieldType = 'String';
9191
}
9292

9393
if (fieldType) {
9494
if (['in', 'nin', 'in[]', 'nin[]'].includes(operatorName)) {
9595
// wrap with GraphQLList, if operator required this with `[]`
9696
const newName = operatorName.slice(-2) === '[]' ? operatorName.slice(0, -2) : operatorName;
97-
fields[newName] = {
98-
...fc,
99-
type: [fieldType],
100-
} as any;
97+
fields[newName] = { type: [fieldType] };
10198
} else {
10299
if (operatorName === 'exists') {
103-
fieldType = 'Boolean';
100+
fields[operatorName] = { type: 'Boolean' };
104101
} else if (operatorName === 'regex') {
105-
fieldType = GraphQLRegExpAsString;
102+
// Only for fields with type String allow regex operator
103+
if (fieldType === GraphQLString) {
104+
fields[operatorName] = { type: GraphQLRegExpAsString };
105+
}
106+
} else {
107+
fields[operatorName] = { type: fieldType } as any;
106108
}
107-
fields[operatorName] = {
108-
...fc,
109-
type: fieldType,
110-
} as any;
111109
}
112110
}
113111
});
@@ -234,11 +232,7 @@ export const _recurseFields = (fields: SelectorOptions): SelectorOptions => {
234232
Object.keys(fields).forEach((fieldName) => {
235233
const operators: string[] = Object.values(availableOperators);
236234
if (operators.includes(fieldName)) {
237-
if (fieldName === 'regex') {
238-
selectors[`$${fieldName}`] = fields[fieldName];
239-
} else {
240-
selectors[`$${fieldName}`] = fields[fieldName];
241-
}
235+
selectors[`$${fieldName}`] = fields[fieldName];
242236
} else {
243237
selectors[fieldName] = _recurseFields(fields[fieldName] as SelectorOptions);
244238
}

0 commit comments

Comments
 (0)