npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dww/graphiql-code-exporter

v2.0.8

Published

Export working code snippets from GraphiQL queries

Downloads

5

Readme

Code Exporter for GraphiQL

A GraphiQL addon that generates ready-to-run code for your queries and mutations.
It provides a wide range of default snippets, but is also extendable with custom snippets.

Bundlesize

Demo

Read the introduction blog post to learn why and how we built it!

Installation

# yarn
yarn add graphiql-code-exporter

# npm
npm i --save graphiql-code-exporter

Built-in Snippets

  • JavaScript
    • fetch
    • react-apollo

< your favorite language/framework/library >

Usage

import React, { Component, Fragment } from 'react'
import GraphiQL from 'graphiql'
import CodeExporter from 'graphiql-code-exporter'
import 'graphiql-code-exporter/CodeExporter.css';

// Optional if you want to use a custom theme
import 'codemirror/theme/neo.css';

const serverUrl = /* your server url here */

export default class GraphiQLWithCodeExporter extends Component {
  state = {
    codeExporterIsVisible: false,
    query: ''
  }

  toggleCodeExporter = () => this.setState({
    codeExporterIsVisible: !this.state.codeExporterIsVisible
  })

  updateQuery = query => this.setState({
    query
  })

  render() {
    const { query, codeExporterIsVisible } = this.state

    const codeExporter = codeExporterIsVisible ? (
      <CodeExporter
        hideCodeExporter={this.toggleCodeExporter}
        snippets={snippets}
        serverUrl={serverUrl}
        context={{
          appId: /* APP_ID */
        }}
        headers={{
          Authorization: 'Bearer ' + /* AUTH_TOKEN */
        }}
        query={query}
        // Optional if you want to use a custom theme
        codeMirrorTheme="neo"
      />
    ) : null

    return (
      <Fragment>
        <GraphiQL
          onEditQuery={this.updateQuery}
          query={query}>
          <GraphiQL.Button
            onClick={this.toggleCodeExporter}
            label="Code Exporter"
            title="Toggle Code Exporter"
          />
        </GraphiQL>
        {codeExporter}
      </Fragment>
    )
  }
}

Props

| Property | Type | Description | | ---------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | hideCodeExporter | Function | A callback function that is called when clicking the close (x) button in the upper right corner of the panel. | | serverUrl | URI | The server url for your GraphQL endpoint. | | query | string | A string containing the GraphQL query that is synced with the GraphiQL query editor. | | snippets | Snippet[] | A list of snippet objects that one can choose from to generate code snippets. | | headers | Object? |  An optional object containing app specific HTTP headers | | context | Object? |  An optional object containing any additional keys required to render app specific snippets | | codeMirrorTheme | string? | The name of the CodeMirror theme you'd like to use e.g. neo. Make sure to also import the theme's css in your code (e.g. import 'codemirror/theme/neo.css') |

Snippets

What we call snippet here, is actually an object with 4 required keys.

| Key | Type | Description | |--------------------------|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------| | name | string | A name that is used to identify the snippet. | | language | string | A language string that is used to group the snippets by language. | | codeMirrorMode | string | A valid CodeMirror mode used for syntax highlighting. Make sure to also require the mode (e.g. import 'codemirror/mode/jsx/jsx' | | options | Option[] | Options are rendered as checkboxes and can be used to customize snippets. They must have an unique id, a label and an initial value of either true or false. | | generate | Function | A function that returns the generated code as a single string. It receives below listed data as an object. | | generateCodesandboxFiles | Function | A function that returns a set of codesandbox files, e.g. {'index.js': {content: 'console.log("hello world")'}}. It receives below listed data as an object. |

Snippet Data

| Key | Type |  Description | | ---------- | ------------- | --------------------------------------------------------------------------------------- | | serverUrl | string | The passed GraphQL server url | | operations | Operation[] | A list of GraphQL operations where each operation has the operation keys. | | options | Object  | A map of option-boolean pairs providing whether an option is selected or not | | headers | Object? | The headers object that is passed to the CodeExporter component | | context | Object? | The context object that is passed to the CodeExporter component |

Operation

| Key |  Type | Description | | ------------ | ----------------------- | --------------------------------------------------------------------------------------------------------- | | name | string | The selected GraphQL operation name | | type | "query" | "mutation" | The selected operation's type | | query |  string |  A formatted string containing the GraphQL operation |   | | variableName | string | The operation name but in UPPER_CASE as that's the common way to declare GraphQL operations in JavaScript | | operation | Object | The plain GraphQL parser result for this operation | | variables | Object |  A map of all used variables for this specific operation |

Example

The following example implements a subset of the built-in Fetch API snippet.
The output will look similar to the demo above.

const fetchSnippet = {
  language: 'JavaScript',
  prismLanguage: 'javascript',
  name: 'Fetch API',
  options: [
    {
      id: 'server',
      label: 'server-side usage',
      initial: false,
    },
  ],
  generate: ({serverUrl, operations, options}) => {
    // we only render the first operation here
    const {query} = operations[0];

    const serverImport = options.server
      ? 'import { fetch } from "node-fetch"'
      : '';

    return `
${serverImport}

const res = await fetch("${serverUrl}", {
  method: 'POST',
  body: JSON.stringify({ query: \`${query}\` }),
})
const { errors, data } = await res.json()

// Do something with the response
console.log(data, errors)
`;
  },
};

Extending the built-in snippets

If we want to use both custom and all the built-in snippets, we can import them from npm.

import snippets from 'graphiql-code-exporter/lib/snippets'

const customSnippet = /* custom snippet */

const extendedSnippets = [
  ...snippets,
  customSnippet
]

This is also useful if you want to filter or modify single snippets.

License

graphiql-code-exporter is licensed under the MIT License. Documentation is licensed under Creative Common License. Created with ♥ by @rofrischmann and all the great contributors.