# graphql-fields

> Turns GraphQLResolveInfo into a map of the requested fields

Latest version **2.0.3** (published 2019-03-05) · MIT license · 0 weekly downloads

## Install

```sh
npm install graphql-fields
pnpm add graphql-fields
yarn add graphql-fields
bun add graphql-fields
```

## Health

**Score 23/100 (F)** — status: abandoned.

Positive: has types package; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.3 |
| Published | 2019-03-05 |
| First published | 2016-02-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | separate (@types/graphql-fields) |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 11.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 345 |
| Author | Rob Richard |
| Maintainers | robrichard |
| Keywords | graphql, graphql-js, graphqlresolveinfo, fields, schema, ast |

## Links

- npm: https://www.npmjs.com/package/graphql-fields
- Repository: https://github.com/robrichard/graphql-fields
- Homepage: https://github.com/robrichard/graphql-fields#readme
- Issues: https://github.com/robrichard/graphql-fields/issues
- npm.io page: https://npm.io/package/graphql-fields

## Alternatives

- [update-check](https://npm.io/package/update-check.md) — 4.0M weekly downloads
- [react-native-onesignal](https://npm.io/package/react-native-onesignal.md) — 134.5K weekly downloads
- [react-redux-toastr](https://npm.io/package/react-redux-toastr.md) — 33.7K weekly downloads
- [@nocobase/plugin-notification-manager](https://npm.io/package/@nocobase/plugin-notification-manager.md) — 2.0K weekly downloads
- [react-simple-toasts](https://npm.io/package/react-simple-toasts.md) — 1.9K weekly downloads

## Recent versions

- 2.0.3 (latest) — 2019-03-05
- 2.0.2 — 2019-02-28
- 2.0.1 — 2018-12-04
- 2.0.0 — 2018-11-29
- 1.3.0 — 2018-11-15
- 1.2.1 — 2018-10-12
- 1.2.0 — 2018-10-10
- 1.1.0 — 2018-07-03
- 1.0.2 — 2017-01-24
- 1.0.1 — 2016-07-31
- 1.0.0 — 2016-02-07

## README

# 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. Takes into account any `@include` or `@skip` directives, excluding fields/fragments which are `@include(if: $false)` or `@skip(if: $true)`.

## Usage

Schema Type definition
```javascript
const graphqlFields = require('graphql-fields');
const graphql = require('graphql')

const UserType = 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},
            nickName: {type: graphql.GraphQLString},
            maidenName: {type: graphql.GraphQLString}
          }
        }),
        email: {type: graphql.GraphQLString},
        id: {type: graphql.GraphQLID}
    }
});

module.exports = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'Query',
        fields: () =>
            Object.assign({
                user: {
                    type: UserType,
                    resolve(root, args, context, info) {
                        console.log(
                            JSON.stringify(graphqlFields(info), null, 2);
                        );
                        ...
                    }
                }
            })
    })
})
```

Query
```graphql
{
  user {
    ...A
    profile {
      ...B
      firstName
    }
  }
}

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

Fragment B on Profile {
  firstName
  nickName @skip(if: true)
}

Fragment C on User {
  email,
  profile {
    middleName
    maidenName @include(if: false)
  }
}
```

will log
```json
{
  "profile": {
    "firstName": {},
    "lastName": {},
    "middleName": {}
  },
  "email": {},
  "id": {}
}

```
### subfields arguments

To enable subfields arguments parsing, you'll have to provide an option object to the function. This feature is disable by default.
```javascript
const graphqlFields = require('graphql-fields');
const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true });
```

For each subfield w/ arguments, a `__arguments` property will be created.
It will be an array with the following format:
```javascript
[
    {
        arg1Name: {
            kind: ARG1_KIND,
            value: ARG1_VALUE,
        },
    },
    {
        arg2Name: {
            kind: ARG2_KIND,
            value: ARG2_VALUE,
        }
    }
]
```

The kind property is here to help differentiate value cast to strings by javascript clients, such as enum values.

### Exclude specific fields 
Most of the time we don't need `__typename` to be sent to backend/rest api, we can exclude `__typename` using this:
```javascript
const graphqlFields = require('graphql-fields');
const fieldsWithoutTypeName = graphqlFields(info, {}, { excludedFields: ['__typename'] });
```
## Why
An underlying REST api may only return fields based on query params.
```graphql
{
  user {
    profile {
      firstName
    },
    id
  }
}
```
should request /api/user?fields=profile,id

while
```graphql
{
  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
```

---
_Source: https://npm.io/package/graphql-fields · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
