Add field directives on Info
It's possible to add a new field on info with the directives of that field?
Reason:
The main reason for this is that using a fieldResolver it'll be possible to add some extra logic on selected fields.
Example:
schema
directive @uppercase on FIELD_DEFINITION
type Me {
email: String!
username: String!
fullName: String! @uppercase
apiKey: String!
}
type Query {
getMe: Me!
}
fieldResolver
function fieldResolver(value, args, ctx, info) {
const result = defaultFieldResolver(value, args, ctx, info)
const uppercase = info.fieldDirectives.find(directive => directive.name.value === 'uppercase')
if (uppercase) {
return result.toUpperCase()
}
return result
}
using express-graphql
app.use('/graphql', (req, res) => {
graphqlHTTP({
schema,
rootValue,
graphiql: true,
fieldResolver
})(req, res)
})
Possible solution
In this method, we can get the directives from fieldDef.astNode.directives
https://github.com/graphql/graphql-js/blob/b8eb8de714e38e414d4e36ae01aea161b352eb13/src/execution/execute.js#L696-L717
Also, if this is accepted, I can work on that
We probably want a more comprehensive solution to getting a directive on various schema definitions.
I think the core idea here is right, but we'd also like to make it easy to access directives for things like type definitions with directives on them.
I think this is possible to do already by grabbing the astNode on the FieldDefinition, but I agree we could use some sort of easier access to the directives. Especially when you throw schema extensions and pure-JS-class created schemas into the mix.
Fwiw graphql-tools has a getDirective method and cousins that might be helpful https://www.graphql-tools.com/docs/api/modules/utils_src#getdirective
Here is my dirty workaround:
import { getDirectives } from '@graphql-tools/utils';
function getDirectivesFromInfo(info: GraphQLResolveInfo) {
const field = info.parentType.getFields()[info.fieldName];
return getDirectives(info.schema, field);
}
It's better if GraphQLResolveInfo contains fieldDef so that we can just pass it to getDirectives function.