Created
February 8, 2019 21:02
-
-
Save trmcnvn/4d4a6397c09ed4343e34a3dc3a611727 to your computer and use it in GitHub Desktop.
GraphQL Directive example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SchemaDirectiveVisitor } from 'graphql-tools'; | |
import { defaultFieldResolver, GraphQLField, GraphQLResolveInfo } from 'graphql'; | |
import { ForbiddenError } from '../errors'; | |
import { ContextParameters } from 'graphql-yoga/dist/types'; | |
// Throws an error if the query requested a field that is marked by this directive | |
// and the requested user is not the authenticated user. | |
export default class OwnerDirective extends SchemaDirectiveVisitor { | |
visitFieldDefinition(field: GraphQLField<any, any>) { | |
this.checkIfOwner(field); | |
} | |
checkIfOwner(field: GraphQLField<any, any>) { | |
const { resolve = defaultFieldResolver } = field; | |
field.resolve = async function( | |
parent: any, | |
args: any, | |
context: ContextParameters & { currentUser: any }, | |
info: GraphQLResolveInfo | |
) { | |
if (context.currentUser.id !== info.variableValues.userId) { | |
throw new ForbiddenError(); | |
} | |
return resolve.call(this, parent, args, context, info); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment