import { SchemaDirectiveVisitor } from "graphql-tools"; import { GraphQLField, GraphQLInterfaceType, GraphQLObjectType } from "graphql"; /** * Authenticate the user, or throws an exception * @param conf */ export const createAuthenticatedVisitor = (conf: { isAuthenticated: (context: any) => boolean; unauthenticatedError: () => Error; }): typeof SchemaDirectiveVisitor => { return class extends SchemaDirectiveVisitor { visitFieldDefinition( field: GraphQLField, details: { objectType: GraphQLObjectType | GraphQLInterfaceType } ): GraphQLField | void | null { let previousResolve = field.resolve; field.resolve = (parent, args, context, info) => { if (!conf.isAuthenticated(context)) throw conf.unauthenticatedError(); return previousResolve(parent, args, context, info); }; } }; };