Skip to content

dividab/graphql-add-remove-fields

Repository files navigation

graphql-add-remove-fields

npm version travis build Coverage Status code style: prettier MIT license

Add or remove fields in graphql queries

Introduction

This package will recursively add or remove a specific field name in all selection sets within the query.

One example usage is adding the __typename field to all selection sets in all outgoing queries and using this together with a normalized cahcing strategy such as graphql-norm to generate a unique ID for each normalized object.

How to install

npm install graphql-add-remove-fields --save

How to use

The package exports two functions, addFields and removeFields. They accept a GraphQL AST and an array of field names to add/remove and returns a new GraphQL AST. The original AST used as input is not modified. Adding fields that already exists will be silently ignored. Removing fields that does not exist will be silently ignored.

Here is a small example:

import gql from "graphql-tag";
import { addFields, removeFields } from "graphql-add-remove-fields";

const query = gql`
  query MyQuery {
    user(id: 10) {
      firstName
      lastName
    }
  }
`;

// This will add the __typename field to all selection sets in the query
const queryAdded = addFields(query, ["__typename"]);

/*
The query is now:
  query MyQuery {
    user(id: 10) {
      firstName
      lastName
      __typename
    }
    __typename
  }
*/

// This will remove the added fields so we will get back the original query
const queryRemoved = removeFields(queryAdded, ["__typename"]);

How to publish

yarn version --patch
yarn version --minor
yarn version --major

About

Add or remove fields in graphql queries

Resources

License

Stars

Watchers

Forks

Packages

No packages published