Giter Club home page Giter Club logo

graphql-fragment-import's Introduction

graphql-fragment-import CI

This monorepo contains three packages:

  • @graphql-fragment-import/cli - an executable to perform graphql module importing
  • @graphql-fragment-import/lib - a library to reuse the underlying code in other libraries programmatically (linting, build tools etc)
  • @graphql-fragment-import/eslint-plugin - an ESLint plugin that augments @eslint-ast/graphql with fragment import support

Import syntax

#import "./_my-fragment.graphql"
#import '../../_my-other-fragment.graphql'
#import "some-package/_its-fragment.graphql"

Usage (as an executable)

npx @graphql-fragment-import/cli <file>
npx @graphql-fragment-import/cli <file> -o <output-file>
npx @graphql-fragment-import/cli <directory> -d <output-directory>
npx @graphql-fragment-import/cli <file> -ir <custom-import-resolver>

Usage (as a library)

yarn add @graphql-fragment-import/lib

or

npm add --save graphql-fragment-import

Combining all imports including transient imports in one string

You can use the function exported from @graphql-fragment-import/lib/inline-imports to combine all the fragment definitions imported directly and transitively in a graphql file.

'use strict';

const fragmentImport = require('@graphql-fragment-import/lib/inline-imports');

const output = fragmentImport(fileContents, {
  resolveImport /* optional: allows the caller to provide an alternative resolution algorithm */,
  resolveOptions: {
    basedir /* required: specifies where to start resolving imported fragments from */,
    ...args /* any other resolve options are passed through to `resolveImport` when resolving imports */
  },
  fs /* optiona: allows for the caller to provide an alternative implementation of node's fs module */
});

output; // contains the grapqhl file, with all imports having been inlined

In the code example above, fileContents is the source code of a .graphql file. The return value is graphql source code with all the fragment definitions in it from all the various files imported.

Helper function for parsing imports for your eslint rule

You can use one of the function exported from @graphql-fragment-import/lib/gather-fragment-imports to find and parse all fragment definitions into FragmentDefinition nodes (for eslint) by import line number.

Here's an example of doing so in an eslint rule.

const { gatherFragmentImportsForContext } = require('@graphql-fragment-import/lib/gather-fragment-imports');

{
  // eslint rule
  create(context)
  {
    return {
      'Document:exit'() {
        /**
         * lineToFragmentNameToBucket is an object whose keys are line numbers and values are objects whose keys are
         * the fragment names and the parsed eslint node:
         * {
         *     1: {
         *         FooBar: FragmentDefinition,
         *         Bar: FragmentDefinition
         *     }
         * }
         */
        const lineToFragmentNameToBucket = gatherFragmentImportsForContext(context, false);

        for (const [lineNumber, fragmentNameToFragment] of Object.entries(lineToFragmentNameToBucket)) {
          // fragmentName is a string and fragment is the object returned by `fragmentParserGenerator`
          for (const [fragmentName, fragment] of Object.entries(fragmentNameToFragment)) {
            // Do something
          }
        }
      }
    }
  }
}

Your consumer projects will need to hav the importResolver and parser setup like configuration in .eslintrc provided below in the "Usage (ESLint)" section.

Usage (ESLint)

// .eslintrc
module.exports = {
  parser: '@eslint-ast/eslint-plugin-graphql/parser',
  parserOptions: {
    schema: 'path/to/schema.graphql',
  },
  plugins: ['@eslint-ast/graphql', '@graphql-fragment-import'],
  extends: [
    'plugin:@eslint-ast/graphql/recommended',
    'plugin:@graphql-fragment-import/recommended',
  ],
  rules: {
    '@graphql-fragment-import/validate-imports': [
      'error',
      // Options only need to be specified if you need a custom import resolver
      // The default is to use require.resolve (i.e. the node resolution algorithm)
      {
        importResolver: require.resolve('ember-cli-addon-aware-resolver'),
      },
    ],
  },
};

Example importable fragments

Given the following files

# // file: _my-fragment.graphql

fragment MyFragment on SomeType {
  fieldC
}
# // file: my-query.graphql
#import './_my-fragment.graphql'

query {
  myQuery {
    fieldA,
    fieldB
    ...MyFragment
  }
}

results in:

npx @graphql-fragment-import/cli ./my-query.graphql
> fragment MyFragment {
>   fieldC
> }
>
> query {
>   myQuery {
>     filedA,
>     fieldB,
>     ...MyFragment
>   }
> }

alternatively, we can provide an input dir and output dir, and let the tool convert many files at once:

npx graphql-fragment-import ./ -d ./output/
>   [processed] my-query.graphql -> ${pwd}/output//my-query.graphql

graphql-fragment-import's People

Contributors

asakusuma avatar brendenpalmer avatar christianarty avatar hjdivad avatar rwjblue avatar stefanpenner avatar zsmoore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  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.