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

@stepzen/graphiql-code-exporter

Package Overview
Dependencies
Maintainers
8
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@stepzen/graphiql-code-exporter

Export working code snippets from GraphiQL queries

  • 4.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
8
Created
Source

Code Exporter for GraphiQL 2

This repo is an experiment in updating the graphiql-code-exporter plugin up to GraphiQL 2.

🚧 the content below is not up-to-date ⬇️

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

PropertyTypeDescription
hideCodeExporterFunctionA callback function that is called when clicking the close (x) button in the upper right corner of the panel.
serverUrlURIThe server url for your GraphQL endpoint.
querystringA string containing the GraphQL query that is synced with the GraphiQL query editor.
snippetsSnippet[]A list of snippet objects that one can choose from to generate code snippets.
headersObject? An optional object containing app specific HTTP headers
contextObject? An optional object containing any additional keys required to render app specific snippets
codeMirrorThemestring?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.

KeyTypeDescription
namestringA name that is used to identify the snippet.
languagestringA language string that is used to group the snippets by language.
codeMirrorModestringA valid CodeMirror mode used for syntax highlighting. Make sure to also require the mode (e.g. import 'codemirror/mode/jsx/jsx'
optionsOption[]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.
generateFunctionA function that returns the generated code as a single string. It receives below listed data as an object.
generateCodesandboxFilesFunctionA 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
KeyType Description
serverUrlstringThe passed GraphQL server url
operationsOperation[]A list of GraphQL operations where each operation has the operation keys.
optionsObject A map of option-boolean pairs providing whether an option is selected or not
headersObject?The headers object that is passed to the CodeExporter component
contextObject?The context object that is passed to the CodeExporter component
Operation
Key TypeDescription
namestringThe selected GraphQL operation name
type"query" | "mutation"The selected operation's type
query string A formatted string containing the GraphQL operation
variableNamestringThe operation name but in UPPER_CASE as that's the common way to declare GraphQL operations in JavaScript
operationObjectThe plain GraphQL parser result for this operation
variablesObject 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.

Keywords

FAQs

Package last updated on 07 Dec 2022

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