Custom scalars vs custom schema directives
At the moment, I'm working on a GraphQL API architecture for my app. And I'm interested in pros and cons in using custom scalars vs. custom schema directives for validation (in the limitations and potential flexibility of each of these approaches).
See, e.g. @okgrow/graphql-scalars for a library of custom GraphQL scalar types for creating precise type-safe GraphQL schemas.
@confuser Did I understand correctly that @constraint directive from graphql-constraint-directive package can only be applied to INPUT_FIELD_DEFINITION, while there are many places where directives (in general) can be applied (see the full list here: https://github.com/graphql/graphql-js/blob/master/src/language/directiveLocation.js)?
Unfortunately yes, due to a bug within graphql-tools. See #1 and https://github.com/apollographql/graphql-tools/issues/789
@confuser This bug was opened more than 8 months ago and still has not been fixed. Do you know how to fix it? If yes, could you please create the pull request for graphql-tools to fix it? This would be a lifesaver.
Does this bug affect only ARGUMENT_DEFINITION or other directive locations like MUTATION, OBJECT, FIELD_DEFINITION, etc. too? If yes, then this is a serious bug. I'm working now on @hasRole(roles_in: [OWNER, ADMIN]) permission directive which should be applied to different locations (mutation, object, field, etc.), and this bug will be a blocker.
@FluorescentHallucinogen No, I do not. I'm not familiar with the graphql-tools codebase. I haven't tested other directive locations.
@confuser
As for the my custom scalars vs. custom schema directives for validation question, I've deep dived into how this package works and realized that it uses custom scalar types under the hood (wraps the field to which the directive is applied into custom scalars). So these are essentially equivalent things. Right?
@FluorescentHallucinogen, this is my understanding as well. From what I can tell, the directives are run through a GraphQL transform using graphql-toosl/utils mapSchema() and end up being replaced by generated scalars.
Closing as this module now supports both
I was going to go try this today and found that the README says:
For GraphQL v15 and below, use v2 of this package
npm install graphql-constraint-directive@v2
If this is true, then we cannot use the server-side plugin method unless we migrate to GraphQL 16?