The current implementation #518 appears to only support query/object type level definitions.
directive @length(max: Int!) on FIELD | FIELD_DEFINITION | INPUT_FIELD_DEFINITION
type Query {
books: [Book]
}
type Book {
title: String
}
type Mutation {
createBook(input: BookInput): Book
}
input BookInput {
title: String! @length(max: 10)
}
When executing a createBook mutation, the length directive resolver never executes. Use case would be to add more granular validation rules via directives. Can be done within the resolver itself, but personally, it feels cleaner to include these at the schema level.
It would be amazing if this was supported.
Happy to open a PR, but fairly new to Typescript, some pointers would be appreciated.
Seems to be due to https://github.com/apollographql/graphql-tools/blob/e1b346aad05f7e356d2cfcd2e619ab9904a81118/src/schemaGenerator.ts#L250-L259 not catering for GraphQLInputObjectType, but obviously this function is used in multiple places...
PR #640 will make this pretty easy:
import { SchemaDirectiveVisitor } from "graphql-tools";
SchemaDirectiveVisitor.visitSchemaDirectives(schema, {
length: class extends SchemaDirectiveVisitor {
public visitInputFieldDefinition(field: GraphQLInputField) {
// This LimitedLengthType should be just like field.type except that the
// serialize method enforces the length limit. For more information about
// GraphQLScalar type serialization, see the graphql-js implementation:
// https://github.com/graphql/graphql-js/blob/31ae8a8e8312494b858b69b2ab27b1837e2d8b1e/src/type/definition.js#L425-L446
field.type = new LimitedLengthType(field.type, this.args.max);
}
}
});
I'm leaving the implementation of LimitedLengthType as an exercise for another time, but I hope the rest of this code demonstrates how to use the SchemaDirectiveVisitor abstraction.
Thanks! Was able to implement this using the SchemaDirectiveVisitor feature, https://github.com/confuser/graphql-constraint-directive for reference
@confuser wow this is really neat - do you want to write a blog post about this package for the Apollo blog? I think a lot of people would be looking for something like this.
Also if you reply here I'm likely to miss it - if you are interested, perhaps DM me on twitter or email me at [email protected]
Most helpful comment
@confuser wow this is really neat - do you want to write a blog post about this package for the Apollo blog? I think a lot of people would be looking for something like this.