How to restrict the use of arguments with directives? #4326
-
Hello! First of all thanks for all the work and awesome tooling ! And here to my problem, I'm trying to port a directive that i've created with graphql-tools v4 to v8. (precisely from apollo-server v2 to v3) Type Query {
myField(myArgument: String @authorize(role: ADMIN))
} on v4 visitArgumentDefinition(argument, details) {
const { resolve: defaultResolver } = defails.field;
const directiveArgument = this.args;
details.field.resolve = function(...resolverArgs) {
const [source, input, cts] = resolverArgs;
if (input[argument.name] && !ctx.user.hasRole(directiveArgument)) throw "UNAUTHORIZED";
return defaultResolver(...resolverArgs);
}
} today using the MapperKind where I'm currently stuck: function directiveTransform(schema) {
return mapSchema(schema, {
[MapperKind.ARGUMENT]: (argumentConfig, fieldName, fieldType) => {
// try to get Field from fieldName
}
})
} Is there a better way to restrict the use of an argument, or simply a way to get a field from it's name ? Thank you for your help ! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Have you found a solution? I have the same problem right now. |
Beta Was this translation helpful? Give feedback.
-
You will need to have to wrap the field resolvers and add validation for the fields like the following. import { mapSchema, MapperKind } from '@graphql-tools/utils';
import { schema } from './schema.js';
mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: fieldConfig => {
// try to get Field from fieldName
if (fieldConfig.args != null) {
// TODO recursively check arguments and wrap resolver function
for (const [_name, field] of Object.entries(fieldConfig.args)) {
const _node = field.astNode?.directives?.find(directive => directive.name.value === 'authorize');
// TODO: gather information on what you want to do in that case
}
return {
...fieldConfig,
resolve: (root, args, context, info) => {
// TODO apply validation here before forwarding to the original resolver
return fieldConfig.resolve?.(root, args, context, info);
},
};
}
return fieldConfig;
},
}); |
Beta Was this translation helpful? Give feedback.
You will need to have to wrap the field resolvers and add validation for the fields like the following.