Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-fields

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-fields

Turns GraphQLResolveInfo into a map of the requested fields

  • 1.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
123K
increased by80.6%
Maintainers
1
Weekly downloads
 
Created
Source

graphql-fields

Turns GraphQLResolveInfo into a map of the requested fields. Flattens all fragments and duplicated fields into a neat object to easily see which fields were requested at any level.

Usage

Schema Type definition

const graphqlFields = require('graphql-fields');
const graphql = require('graphql')

module.exports = new graphql.GraphQLObjectType({
    name: 'User',
    fields: {
        profile: {type: new graphql.GraphQLObjectType({
          name: 'Profile',
          fields: {
            firstName: {type: graphql.GraphQLString},
            lastName: {type: graphql.GraphQLString},
            middleName: {type: graphql.GraphQLString}
          }
        }),
        email: {type: graphql.GraphQLString},
        id: {type: graphql.GraphQLID}
    },
    resolve(root, args, context, info) {
      console.log(
        JSON.stringify(graphqlFields(info), null, 2);
      );
      ...
    }
});

Query

{
  user {
    ...A
    profile {
      ...B
      firstName
    }
  }
}

fragment A on User {
  ...C
  id,
  profile {
    lastName
  }
}

Fragment B on Profile {
  firstName
}

Fragment C on User {
  email,
  profile {
    middleName
  }
}

will log

{
  "profile": {
    "firstName": {},
    "lastName": {},
    "middleName": {}
  },
  "email": {},
  "id": {}
}

Why

An underlying REST api may only return fields based on query params.

{
  user {
    profile {
      firstName
    },
    id
  }
}

should request /api/user?fields=profile,id

while

{
  user {
    email
  }
}

should request /api/user?fields=email

Implement your resolve method like so:

resolve(root, args, context, info) {
    const topLevelFields = Object.keys(graphqlFields(info));
    return fetch(`/api/user?fields=${topLevelFields.join(',')}`);
}

Tests

npm test

Keywords

FAQs

Package last updated on 24 Jan 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc