Giter Club home page Giter Club logo

graphql-introspection-filtering's Introduction

graphql-introspection-filtering

Filter graphql schema introspection result to hide restricted fields and types. It allows using extended SchemaDirectiveVisitors or filter functions to decide which schema nodes will be returned with introspection result

NOTE: For successful introspection all dependent types must be returned. If any of dependent types is missing it won't be possible to rebuild graph on client side i.e. graphql playground is unable to build interactive documentation.

Installation

yarn add graphql-introspection-filtering

Usage

Make filtered schema

Most important thing is to wrap executable graphql schema with makeFilteredSchema too add filters

const schema = makeFilteredSchema(executableSchema, filters);
  • executableSchema - Executable schema created with makeExecutableSchema
  • filters - Filters definition

Filters definition

Object that holds a set of schema node filters

const filters = {
    field: [],
    type: [],
    directive: []
};
  • field - (optional) Array of filter functions to filter fields
  • type - (optional) Array of filter functions to filter types
  • directive - (optional) Array of filter functions to filter directives

Filter function

Node filtering function, when result of this function is true the node will be returned

(field, root, args, context, info) => boolean;
  • field - Schema node to be returned, the node we decide whether we want to show it or not
  • root - Root node for this introspection request as for regular query
  • args - Arguments for this introspection request as for regular query
  • context - Query context for this introspection request as for regular query
  • info - Query info for this introspection request as for regular query

Pick filters from schema visitors

This function creates filters definition from schemaDirectives based on static methods in SchemaDirectiveVisitors.

const filters = schemaDirectivesToFilters(schemaDirectives);
  • schemaDirectives - Set of schemaDirectives provided to makeExecutableSchema

Example with directives

Example filtering schema introspection and checking permissions on fields, objects and enums with directives

Configure graphql schema structure

enum Role @auth(requires: ADMIN) {
    ADMIN
    REVIEWER
    USER
    UNKNOWN
}

directive @auth(
    requires: Role = ADMIN,
) on OBJECT | FIELD_DEFINITION | ENUM

type Book @auth(requires: ADMIN) {
    title: String
    author: String
}

type Query {
    me: User
    books: [Book] @auth(requires: ADMIN)
}

Make filtered schema

import makeFilteredSchema, { schemaDirectivesToFilters } from 'graphql-introspection-filtering';

const schema = makeFilteredSchema(
   makeExecutableSchema({
       typeDefs,
       resolvers,
       schemaDirectives
   }),
   schemaDirectivesToFilters(schemaDirectives)
);

AuthenticationDirective

class AuthenticationDirective extends SchemaDirectiveVisitor {
    static RequiredRole = Symbol('RequiredRole');
    
    _wrappedSymbol = Symbol('wrapped');

    // filter introspection types
    static visitTypeIntrospection(field, _, __, context) {
        return AuthenticationDirective.isAccessible(field, context);
    }

    // filter introspection fields
    static visitFieldIntrospection(field, _, __, context) {
        return AuthenticationDirective.isAccessible(field, context);
    }

    // filter introspection directives
    static visitDirectiveIntrospection({ name }) {
        return name !== 'auth';
    }

    // decide if user has access to the node
    static isAccessible(field, context) {
        const requiredAuthRole = field[AuthenticationDirective.RequiredRole];

        if (requiredAuthRole) {
            if (!context || !context.user || !context.user.roles.includes(requiredAuthRole)) {
                return false;
            }
        }

        return true;
    }
    
    constructor(...args) {
        super(...args);

        this.ensureFieldWrapped = this.ensureFieldWrapped.bind(this);
    }

    ensureFieldWrapped(field) {
        if (field[this._wrappedSymbol]) return;
        field[this._wrappedSymbol] = true;

        const { resolve = defaultFieldResolver } = field;

        field.resolve = this.wrapField.call(this, resolve, field);
    }

    visitObject(obj) {
        this.ensureFieldWrapped(obj);
        obj[AuthenticationDirective.RequiredRole] = this.args.requires;
    }

    visitEnum(en) {
        this.ensureFieldWrapped(en);
        en[AuthenticationDirective.RequiredRole] = this.args.requires;
    }

    visitFieldDefinition(field) {
        this.ensureFieldWrapped(field);
        field[AuthenticationDirective.RequiredRole] = this.args.requires;
    }

    wrapField(resolve, field) {
        return async (root, args, context, info) => {
            if (!AuthenticationDirective.isAccessible(field, context)) {
                throw new Error('Not authorized!');
            }

            return resolve.call(this, root, args, context, info);
        };
    }
}

graphql-introspection-filtering's People

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.