I have a node project using GraphQL(v16.7.0) and the @graphql-tools/utils
library, attempting to setup a nonEmptyArray
custom schema directive to throw an error whenever a mutation is called with an empty array for an input. It would be used like this:
input ExampleInput {
ids: [String!]! @nonEmptyArray
}
The code I have so far is:
const getNonEmptyArrayDirective = (schema: GraphQLSchema): SchemaMapper => ({
[MapperKind.INPUT_OBJECT_FIELD]: (
fieldConfig: GraphQLInputFieldConfig,
fieldName: string,
typeName: string,
) => {
const directive = getDirective(schema, fieldConfig, 'nonEmptyArray')?.[0];
if (directive) {
fieldConfig.extensions = {
...fieldConfig.extensions,
validateInput: inputValue => {
console.log({inputValue})
if (Array.isArray(inputValue)) {
if (inputValue.length === 0) {
throw new EmptyArrayError(fieldName);
}
}
return inputValue;
},
};
}
return fieldConfig;
},
});
export default function applySchemaDirectives(
schema: GraphQLSchema,
): GraphQLSchema {
schema = mapSchema(schema, getNonEmptyArrayDirective(schema));
return schema;
}
and declaring the directive:
directive @nonEmptyArray on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
So far I can’t even get the console.log({inputValue})
to execute. I’ve experimented with adding other MapperKind
values such as MapperKind.SCALAR_TYPES
and those do log properly, implying it’s not a problem with the general setup of the custom directive. My impression is that the issue has something to do with the way GraphQL specifically handles list types.