Reputation: 3830
In Apollo Server, one could use a schema directive to implement a resolver middleware like such:
adminGetUsers(getUsersPL: GetUsersPL!): [User] @hasRole(role: "ADMIN")
@hasRole(role: "ADMIN")
serves as a middleware to prevent any non-admin user from using this mutation.
So how would one sanitize/transform input data? For example,
getUser(userId: String! @transform): [User]
@transform
will take in userId as a hashed id (ie: xyfd
), and transform it to a numbered ID (ie: 12
). This syntax is not allowed of course. Basically I want a way to modify input data before it goes into resolver.
Upvotes: 1
Views: 1485
Reputation: 84687
That actually is valid syntax. You can define a directive that's applied to argument definitions like this:
directive @test on ARGUMENT_DEFINITION
type Query {
foo(input: String @test): String
}
Schema directives are not middleware. They are just ways of altering individual definitions inside your schema. Most commonly they are used to alter field definitions, but you can alter other definitions like object types, input object types, enums, unions, etc. When using a directive with a field, you can wrap the existing resolve function inside another one (or replace it altogether) -- in doing so, we can create "middleware" for resolvers. However, that's not the purpose of schema directives.
That aside, you can't use an argument directive to alter the value the argument is passed. At best, you can change the type of the argument to something else (like a custom scalar). However, you can just use a field directive to do what you're trying to accomplish:
class ExampleDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field
field.resolve = async function (
source,
args,
context,
info,
) {
args.someArg = doSomething(args.someArg)
return resolve.call(this, source, args, context, info);
}
}
}
Upvotes: 2