Unveiling the Mock GraphQL Tool

2023-09-24

🚀 Exciting news! Today, we present a closer look at our new tool: graphql-mock.

Find it at graphql-mock.devtoolsdaily.com. This tool allows you to input your GraphQL schema and receive mock data based on your schema.

Key Features:

  • Customizable GraphiQL UI: Input your GraphQL schema and get corresponding mock data.
  • Browser-Based: No backend setup required, and it generates shareable URLs.
  • Uses: Showcase GraphQL queries, experiment with SDL, and understand GraphQL, all without a dedicated GraphQL server.

Usage:

  1. Visit https://graphql-mock.devtoolsdaily.com
  2. Access the 'Set SDL Schema' pane. open Set SDL Schema pane
  3. Input your schema and click 'Save'. set schema and click save
  4. Enter your query to receive mock data. write your query
  5. The browser URL updates as per your schema and query configurations for easy sharing.

Technical Breakdown:

  1. GraphiQL React Library: This renders our GraphiQL UI.
  2. Mock API Integration: Instead of pointing the Graphql UI to a standard backend, we use mock data. This handles both introspection queries and the custom user queries.
import { makeExecutableSchema } from '@graphql-tools/schema';
import { addMocksToSchema } from '@graphql-tools/mock'

const schema = makeExecutableSchema({
  typeDefs
});

const schemaWithMocks = addMocksToSchema({ schema })
  1. Connecting GraphQL with Mocked Schema: GraphiQL uses a fetcher function to execute queries.
function fetcher({ query, variables }) {
  return graphql({
    schema: schemaWithMocks,
    source: query
})
}

<GraphiQL  fetcher={fetcher}  />
  1. SDL Schema Editing in GraphiQL: GraphiQL allows for plugins. Create a JSON object with the necessary fields and integrate it with GraphiQL.

All you need to do is to create a JSON object with 3 fields, and pass it to GraphiQL.

  const editSdlPlugin = {
    title: 'Edit SDL',
    icon: () => (pencilIcon),
    content: () => <EditSdlPlugin />
  }

<GraphiQL  fetcher={fetcher} plugins={[editSdlPlugin]} />

  1. capturing state of Query and GraphQL schema in the URL.

GraphiQL takes some props:

  • onEditQuery - called when Query changed
  • defaultQuery to set default Query shown when UI is first open. Using query instead of defaultQuery will result in an extra tab.
<GraphiQL defaultQuery={defaultQuery} onEditQuery={editedQuery => setQuery(editedQuery)}
  1. State Compression: Using `LZString``, we can compress larger objects into URL-friendly strings.
import LZString from 'lz-string';

function compress(s) {
  return LZString.compressToEncodedURIComponent(s);
}

Take it for a spin and let us know your feedback. 🚀

graphql-mock.devtoolsdaily.com