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:
- Visit https://graphql-mock.devtoolsdaily.com
- Access the 'Set SDL Schema' pane.
- Input your schema and click 'Save'.
- Enter your query to receive mock data.
- The browser URL updates as per your schema and query configurations for easy sharing.
Technical Breakdown:
- GraphiQL React Library: This renders our GraphiQL UI.
- 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 })
- 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} />
- 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]} />
- capturing state of Query and GraphQL schema in the URL.
GraphiQL takes some props:
onEditQuery
- called when Query changeddefaultQuery
to set default Query shown when UI is first open. Usingquery
instead ofdefaultQuery
will result in an extra tab.
<GraphiQL defaultQuery={defaultQuery} onEditQuery={editedQuery => setQuery(editedQuery)}
- 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. 🚀