Skip to content

Instantly share code, notes, and snippets.

@trmcnvn
Created February 8, 2019 21:02
Show Gist options
  • Save trmcnvn/4d4a6397c09ed4343e34a3dc3a611727 to your computer and use it in GitHub Desktop.
Save trmcnvn/4d4a6397c09ed4343e34a3dc3a611727 to your computer and use it in GitHub Desktop.
GraphQL Directive example
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