### Vanilla JavaScript with GraphRef
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedExplorer.md
Example of initializing the Apollo Explorer using Vanilla JavaScript with a graph reference. Includes basic state and cleanup.
```javascript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer-container',
graphRef: 'my-graph@production',
initialState: {
document: 'query { user { id name } }',
displayOptions: {
theme: 'light',
showHeadersAndEnvVars: true,
},
},
});
// Clean up
explorer.dispose();
```
--------------------------------
### Setting Initial State
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/README.md
Pre-populates the explorer with a document, variables, headers, and display options. This allows for a customized starting point.
```typescript
new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
initialState: {
document: `query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}`,
variables: { id: '123' },
headers: { 'Authorization': 'Bearer token' },
displayOptions: {
theme: 'light',
showHeadersAndEnvVars: true,
},
},
});
```
--------------------------------
### Tree-Shaking Example: Importing Only Helpers (ESM)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Demonstrates tree-shaking by importing only the explorer-helpers from the ESM build, resulting in a smaller bundle size.
```typescript
// Only helpers imported
import { readMultipartWebStream } from '@apollo/explorer-helpers'; // ~2 KB
```
--------------------------------
### Basic ApolloExplorerReact Setup with GraphRef
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloExplorerReact.md
Demonstrates the simplest way to embed the Apollo Explorer using a graph reference. This is useful for connecting to an existing Apollo Studio graph.
```typescript
import { ApolloExplorer } from '@apollo/explorer/react';
function App() {
return (
);
}
```
--------------------------------
### Tree-Shaking Example: Importing Only Apollo Explorer (ESM)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Demonstrates tree-shaking by importing only the Apollo Explorer from the ESM build, resulting in a smaller bundle size.
```typescript
// Only Explorer imported
import { ApolloExplorer } from '@apollo/explorer'; // ~40 KB
```
--------------------------------
### Custom HandleRequest Implementation Example
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/types.md
Example of implementing a custom network request handler. This handler adds an 'Authorization' header to outgoing requests.
```typescript
const customHandler: HandleRequest = (url, options) => {
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': 'Bearer token',
},
});
};
new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
handleRequest: customHandler,
});
```
--------------------------------
### Include Apollo Sandbox via UMD Script Tag
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Example of including the Apollo Sandbox using a UMD script tag and initializing it.
```html
```
--------------------------------
### Minimal ApolloSandboxReact Setup
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloSandboxReact.md
Use this snippet for a basic integration of Apollo Sandbox in your React application. It requires the initial GraphQL endpoint URL.
```typescript
import { ApolloSandbox } from '@apollo/sandbox/react';
function App() {
return (
);
}
```
--------------------------------
### Include Apollo Explorer via UMD Script Tag
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Example of including the Apollo Explorer using a UMD script tag and initializing it.
```html
```
--------------------------------
### Recommended Custom Handler for Credentials
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/defaultHandleRequest.md
This example demonstrates the recommended approach for handling credentials by implementing a custom handleRequest function. This provides explicit control over the 'credentials' setting in fetch.
```typescript
// Recommended:
new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
handleRequest: async (url, options) => {
return fetch(url, {
...options,
credentials: 'include',
});
},
});
```
--------------------------------
### Initialize Embedded Explorer for Local Development
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/explorer/src/examples/localDevelopmentExample.html
Instantiates the Embedded Explorer with specific configurations for local testing. Ensure the target DOM element exists before this script runs. This setup is useful for quickly previewing your GraphQL schema and queries during development.
```javascript
new window.EmbeddedExplorer({
target: '#embeddableExplorer',
__testLocal__: true,
graphRef: 'Multi-part-subs-monolith@current',
initialState: {
document: `query Example { me { id } }`,
variables: {
test: 'abcxyz',
},
displayOptions: {
showHeadersAndEnvVars: true,
},
},
});
```
--------------------------------
### Setup Embed Relay for Explorer
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/API_REFERENCE.md
Sets up postMessage relay for the embeddable Explorer. This function is intended for internal use by EmbeddedExplorer.
```typescript
function setupEmbedRelay({
endpointUrl,
handleRequest,
embeddedExplorerIFrameElement,
updateSchemaInEmbed,
schema,
graphRef,
autoInviteOptions,
__testLocal__,
}): DisposableResource
```
--------------------------------
### With Custom Request Handler
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedExplorer.md
Example of configuring the Apollo Explorer with a custom request handler to modify network requests, such as adding authentication headers.
```javascript
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
handleRequest: async (url, options) => {
// Add custom auth header
const headers = {
...options.headers,
'X-Custom-Auth': 'token-123',
};
return fetch(url, { ...options, headers });
},
});
```
--------------------------------
### Minimal Embedded Sandbox Initialization (Vanilla JavaScript)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedSandbox.md
Demonstrates the basic setup for embedding Apollo Sandbox using Vanilla JavaScript. Ensure you have a target element with the ID 'sandbox-container' in your HTML.
```typescript
import { ApolloSandbox } from '@apollo/sandbox';
const sandbox = new ApolloSandbox({
target: '#sandbox-container',
initialEndpoint: 'http://localhost:4000/graphql',
});
sandbox.dispose();
```
--------------------------------
### Setup Sandbox Embed Relay
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/API_REFERENCE.md
Sets up postMessage relay for the embeddable Sandbox. This function is intended for internal use by EmbeddedSandbox.
```typescript
function setupSandboxEmbedRelay({
handleRequest,
embeddedSandboxIFrameElement,
__testLocal__,
}): DisposableResource
```
--------------------------------
### Setup Sandbox Embed Relay Function Signature
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupSandboxEmbedRelay.md
This is the function signature for setting up the postMessage relay. It takes configuration options and returns a disposable resource.
```typescript
function setupSandboxEmbedRelay({
handleRequest,
embeddedSandboxIFrameElement,
__testLocal__,
}: {
handleRequest: HandleRequest;
embeddedSandboxIFrameElement: HTMLIFrameElement;
__testLocal__: boolean;
}): DisposableResource
```
--------------------------------
### ApolloExplorerReact with Dynamic Schema Updates
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloExplorerReact.md
Demonstrates how to dynamically update the explorer's schema by polling an endpoint. This example fetches schema updates periodically without recreating the iframe.
```typescript
import { ApolloExplorer } from '@apollo/explorer/react';
import { useEffect, useState } from 'react';
function DynamicSchemaExplorer() {
const [schema, setSchema] = useState(null);
useEffect(() => {
// Poll for schema updates
const interval = setInterval(async () => {
const response = await fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: getIntrospectionQuery() }),
});
const { data } = await response.json();
setSchema(data.__schema);
}, 5000);
return () => clearInterval(interval);
}, []);
if (!schema) return
Loading schema...
;
return (
);
}
```
--------------------------------
### GraphQL Error Response Example
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/README.md
Illustrates the structure of an error response from a GraphQL API, including the message and path for each error. This format is used for UI rendering within the embed.
```typescript
{
data: null,
errors: [
{ message: 'Unauthorized', path: [] },
],
}
```
--------------------------------
### Explicit Credentials Control with defaultHandleRequest
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/defaultHandleRequest.md
This example demonstrates explicitly controlling cookie behavior by passing true to legacyIncludeCookies in defaultHandleRequest. This forces credentials to be included with every request.
```typescript
import { defaultHandleRequest } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
// Always include credentials
handleRequest: defaultHandleRequest({ legacyIncludeCookies: true }),
});
```
--------------------------------
### Execute GraphQL Subscription
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/RequestExecution.md
Executes a GraphQL subscription using either WebSocket or multipart HTTP protocols. It handles connection setup, message passing, and status updates for different subscription protocols.
```typescript
async function executeSubscription({
subscriptionUrl,
operation,
operationName,
variables,
headers,
embeddedIFrameElement,
operationId,
embedUrlOrigin,
protocol,
handleRequest,
httpMultipartParams,
}: {
subscriptionUrl: string;
operation: string;
operationName: string | undefined;
variables?: Record;
headers?: Record;
embeddedIFrameElement: HTMLIFrameElement;
operationId: string;
embedUrlOrigin: string;
protocol: GraphQLSubscriptionLibrary;
handleRequest: HandleRequest;
httpMultipartParams: { includeCookies: boolean | undefined };
}): Promise
```
```typescript
// Executed when embed sends EXPLORER_SUBSCRIPTION_REQUEST
await executeSubscription({
subscriptionUrl: 'ws://localhost:4000/graphql',
operation: 'subscription OnMessage { messageAdded { text } }',
operationId: 'sub-456',
embeddedIFrameElement: iframeEl,
operationName: 'OnMessage',
variables: {},
headers: {},
embedUrlOrigin: 'https://explorer.embed.apollographql.com',
protocol: 'graphql-ws',
handleRequest: async (url, opts) => fetch(url, opts),
httpMultipartParams: { includeCookies: false },
});
```
--------------------------------
### Initialize Apollo Sandbox (Default)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Demonstrates how to initialize the Apollo Sandbox using its default entry point. Requires a target DOM element and an initial GraphQL endpoint.
```typescript
import { ApolloSandbox } from '@apollo/sandbox';
const sandbox = new ApolloSandbox({
target: '#sandbox',
initialEndpoint: 'http://localhost:4000/graphql',
});
```
--------------------------------
### ApolloExplorerReact with Initial Query and Variables
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloExplorerReact.md
Shows how to pre-populate the explorer with an initial GraphQL query, variables, and display options. Persists explorer state across sessions using localStorage.
```typescript
import { ApolloExplorer } from '@apollo/explorer/react';
function MyExplorer() {
return (
);
}
```
--------------------------------
### Embedded Sandbox with Initial Query and Variables
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedSandbox.md
Shows how to configure the initial state of the sandbox, including a GraphQL query, variables, and headers. This is useful for pre-populating the sandbox with specific data or queries.
```typescript
import { ApolloSandbox } from '@apollo/sandbox';
const sandbox = new ApolloSandbox({
target: '#sandbox',
initialEndpoint: 'https://api.example.com/graphql',
initialState: {
document: `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`,
variables: {
id: '123',
},
headers: {
'Authorization': 'Bearer token-here',
},
pollForSchemaUpdates: true,
},
});
```
--------------------------------
### EmbeddableSandboxOptions Interface Definition
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/types.md
Configuration options for embedded Sandbox. All options are optional, allowing for flexible setup of the GraphQL sandbox environment.
```typescript
export interface EmbeddableSandboxOptions {
target: string | HTMLElement;
initialEndpoint?: string;
initialSubscriptionEndpoint?: string;
initialState?: InitialState;
runTelemetry?: boolean;
handleRequest?: HandleRequest;
includeCookies?: boolean;
hideCookieToggle?: boolean;
endpointIsEditable?: boolean;
allowDynamicStyles?: boolean;
sendOperationHeadersInIntrospection?: boolean;
}
```
--------------------------------
### With Custom Schema and Endpoint
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedExplorer.md
Demonstrates initializing the Apollo Explorer with a custom GraphQL schema and endpoint URL. Requires importing `buildSchema` from 'graphql'.
```javascript
import { ApolloExplorer } from '@apollo/explorer';
import { buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
hello: String
}
`);
const explorer = new ApolloExplorer({
target: document.getElementById('explorer'),
schema,
endpointUrl: 'http://localhost:4000/graphql',
initialState: {
document: 'query { hello }',
variables: { test: 'value' },
},
});
```
--------------------------------
### Embeddable Explorer Initialization
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ARCHITECTURE.md
Illustrates the initialization flow for the EmbeddedExplorer, including option validation, iframe creation, and setting up message relay listeners for communication with the embedded Explorer iframe.
```javascript
new EmbeddedExplorer({ target, schema, endpointUrl })
↓
1. Validate options
2. Create iframe with encoded query params (initial state)
3. Append iframe to target element
4. setupEmbedRelay() — register message listeners
├─ Listen for EXPLORER_LISTENING_FOR_HANDSHAKE
├─ Listen for EXPLORER_LISTENING_FOR_SCHEMA
├─ Listen for EXPLORER_QUERY_MUTATION_REQUEST
├─ Listen for EXPLORER_SUBSCRIPTION_REQUEST
└─ Listen for authentication messages
5. Explorer iframe loads and connects via postMessage
├─ Sends EXPLORER_LISTENING_FOR_HANDSHAKE
├─ Parent responds with graphRef/account info
├─ Sends EXPLORER_LISTENING_FOR_SCHEMA
└─ Parent sends schema via SCHEMA_RESPONSE
```
--------------------------------
### Get File List From Transfer Function Signature
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Signature for the getFileListFromTransfer function, which converts ArrayBuffer file variables to File objects.
```typescript
function getFileListFromTransfer({
fileVariables,
}): FileVariable[]
```
--------------------------------
### Embedded Explorer Initialization with Schema and Endpoint
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupEmbedRelay.md
Demonstrates how to initialize the EmbeddedExplorer using a local schema and endpoint URL. The setupEmbedRelay function is called internally by the constructor.
```typescript
import { EmbeddedExplorer } from '@apollo/explorer';
const explorer = new EmbeddedExplorer({
target: '#explorer',
schema: introspectionResult,
endpointUrl: 'http://localhost:4000/graphql',
});
```
--------------------------------
### Apollo Sandbox - Default Entry Point
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
The main Apollo Embeddable Sandbox package. Use this for direct integration into your application.
```APIDOC
## @apollo/sandbox
### Description
Provides the core functionality for embedding the Apollo Sandbox.
### Method
`new`
### Constructor Parameters
- **`target`** (string) - Required - The CSS selector for the DOM element where the sandbox will be mounted.
- **`initialEndpoint`** (string) - Required - The GraphQL endpoint to connect to.
### Request Example
```javascript
import { ApolloSandbox } from '@apollo/sandbox';
const sandbox = new ApolloSandbox({
target: '#sandbox',
initialEndpoint: 'http://localhost:4000/graphql',
});
```
### Response
N/A (Constructor does not return a value, it initializes the sandbox in the target element.)
```
--------------------------------
### ApolloSandboxReact with Initial Query and Headers
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloSandboxReact.md
Configure the sandbox with an initial GraphQL query, variables, and custom headers. This is useful for pre-populating the sandbox with a specific state or authentication details.
```typescript
import { ApolloSandbox } from '@apollo/sandbox/react';
function MySandbox() {
return (
);
}
```
--------------------------------
### Apollo Explorer - Default Entry Point
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
The main Apollo Embeddable Explorer package. Use this for direct integration into your application.
```APIDOC
## @apollo/explorer
### Description
Provides the core functionality for embedding the Apollo Explorer.
### Method
`new`
### Constructor Parameters
- **`target`** (string) - Required - The CSS selector for the DOM element where the explorer will be mounted.
- **`graphRef`** (string) - Required - The reference to the Apollo graph to load.
### Request Example
```javascript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@production',
});
```
### Response
N/A (Constructor does not return a value, it initializes the explorer in the target element.)
```
--------------------------------
### Use Apollo Sandbox React Component
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/sandbox/README.md
Render the ApolloSandbox React component within your application to embed the sandbox. No additional configuration is shown in this basic example.
```javascript
import { ApolloSandbox } from '@apollo/sandbox/react';
function App() {
return (
);
}
```
--------------------------------
### Embedded Explorer Initialization with GraphRef (Studio Graph)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupEmbedRelay.md
Shows how to initialize the EmbeddedExplorer using a graphRef for connecting to a Studio graph. A custom handleRequest function is provided for authentication.
```typescript
const explorer = new EmbeddedExplorer({
target: '#explorer',
graphRef: 'my-graph@production',
handleRequest: async (url, opts) => {
return fetch(url, {
...opts,
headers: {
...opts.headers,
'Authorization': `Bearer ${getToken()}`,
},
});
},
});
```
--------------------------------
### Import Apollo Explorer and Sandbox with Types (TypeScript)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Import patterns for Apollo Explorer and Apollo Sandbox including type definitions using TypeScript.
```typescript
import { ApolloExplorer, EmbeddableExplorerOptions } from '@apollo/explorer';
import { ApolloSandbox, EmbeddableSandboxOptions } from '@apollo/sandbox';
import type { FileVariable, MultipartResponse } from '@apollo/explorer-helpers';
```
--------------------------------
### Custom Request Handling for Debugging
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/README.md
Provides an example of a custom `handleRequest` function to log outgoing requests and incoming response statuses. This is useful for debugging network and authentication issues.
```typescript
handleRequest: async (url, options) => {
console.log('Request:', { url, options });
const response = await fetch(url, options);
console.log('Response:', response.status);
return response;
}
```
--------------------------------
### Initialize Apollo Explorer
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/README.md
Instantiate the main class for embedding Apollo Studio's GraphQL Explorer. Connect to Apollo Studio graphs via `graphRef` or provide a custom schema and endpoint. Supports initial state, custom request handlers, and automatic authentication.
```typescript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer-container',
graphRef: 'my-graph@production',
});
```
--------------------------------
### Apollo Sandbox - React Entry Point
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
The React-specific entry point for the Apollo Embeddable Sandbox. Use this if you are working within a React application.
```APIDOC
## @apollo/sandbox/react
### Description
Provides a React component for embedding the Apollo Sandbox.
### Component
`ApolloSandbox`
### Props
- **`initialEndpoint`** (string) - Required - The GraphQL endpoint to connect to.
### Request Example
```javascript
import { ApolloSandbox } from '@apollo/sandbox/react';
function MyApp() {
return ;
}
```
### Response
N/A (This is a React component.)
```
--------------------------------
### Deprecated includeCookies Usage
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/defaultHandleRequest.md
This example shows the deprecated way of handling cookies in Apollo Explorer using the includeCookies option. It is recommended to use a custom handleRequest function instead.
```typescript
// Deprecated (legacy):
new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
includeCookies: true, // ❌ Deprecated
});
```
--------------------------------
### Custom Handler Overriding Default
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/defaultHandleRequest.md
This example shows how to completely replace the default request handler with a custom function. The custom handler can implement any logic, such as adding authorization headers.
```typescript
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
// Custom handler completely replaces defaultHandleRequest
handleRequest: async (url, options) => {
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${getToken()}`,
},
});
},
});
```
--------------------------------
### Default Handler (No Credentials Management)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/defaultHandleRequest.md
This example shows how to use the default request handler by not providing a custom handleRequest function to ApolloExplorer. It internally uses defaultHandleRequest() with undefined legacyIncludeCookies.
```typescript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@current',
// handleRequest not provided, uses defaultHandleRequest()
});
// Internally equivalent to:
// handleRequest: defaultHandleRequest({ legacyIncludeCookies: undefined })
```
--------------------------------
### Initialize Embedded Explorer with Manual Schema
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/explorer/src/examples/manualSchema.html
Instantiates the Embedded Explorer with a target DOM element, GraphQL endpoint, and a manually provided schema. This is useful when the schema is not available via introspection.
```javascript
const getExampleSchema = () => `"""The basic book in the graph""" type Book implements Product { """All books can be found by an isbn""" isbn: String! """The title of the book""" title: String """The year the book was published""" year: Int """A simple list of similar books""" similarBooks: [Book] """ Since books are now products, we can also use their upc as a primary id """ upc: String! """The name of a book is the book's title + year published""" name(delimeter: String = " "): String price: Int weight: Int reviews: [Review] reviewList(first: Int = 5, after: Int = 0): ReviewConnection """ relatedReviews for a book use the knowledge of similarBooks from the books service to return related reviews that may be of interest to the user """ relatedReviews(first: Int = 5, after: Int = 0): ReviewConnection }
"""Information about the brand Ikea""" type Ikea { """Which asile to find an item""" asile: Int }
"""Information about the brand Amazon""" type Amazon { """The url of a referrer for a product""" referrer: String }
"""A union of all brands represented within the store""" union Brand = Ikea | Amazon enum ProductType { LATEST TRENDING }
type PageInfo { hasNextPage: Boolean hasPreviousPage: Boolean }
"""A connection edge for the Product type""" type ProductEdge { product: Product }
"""A connection wrapper for lists of products""" type ProductConnection { """Helpful metadata about the connection""" pageInfo: PageInfo """List of products returned by the search""" edges: [ProductEdge] }
"""The Product type represents all products within the system""" interface Product { """The primary identifier of products in the graph""" upc: String! """The display name of the product""" name: String """A simple integer price of the product in US dollars""" price: Int """How much the product weighs in kg""" weight: Int @deprecated(reason: "Not all product's have a weight") """A simple list of all reviews for a product""" reviews: [Review] @deprecated(reason: "The reviews field on product is deprecated to roll over the return type from a simple list to a paginated list. The easiest way to fix your operations is to alias the new field reviewList to review") """ A paginated list of reviews. This field naming is temporary while all clients migrate off of the un-paginated version of this field call reviews. To ease this migration, alias your usage of reviewList to reviews so that after the roll over is finished, you can remove the alias and use the final field name: { ... on Product { reviews: reviewList { edges { review { body } } } } } """ reviewList(first: Int = 5, after: Int = 0): ReviewConnection }
""" The Furniture type represents all products which are items of furniture. """ type Furniture implements Product { """The modern primary identifier for furniture""" upc: String! """ The SKU field is how furniture was previously stored, and still exists in some legacy systems """ sku: String! name: String price: Int """The brand of furniture""" brand: Brand weight: Int reviews: [Review] reviewList(first: Int = 5, after: Int = 0): ReviewConnection }
"""The base User in Acephei""" type User { """A globally unique id for the user""" id: ID! """The users full name as provided""" name: String """The account username of the user""" username: String """A list of all reviews by the user""" reviews: [Review] }
"""A review is any feedback about products across the graph""" type Review { id: ID! """The plain text version of the review""" body: String """The user who authored the review""" author: User """The product which this review is about""" product: Product }
"""A connection edge for the Review type""" type ReviewEdge { review: Review }
"""A connection wrapper for lists of reviews""" type ReviewConnection { """Helpful metadata about the connection""" pageInfo: PageInfo """List of reviews returned by the search""" edges: [ReviewEdge] }
type Query { """Fetch a simple list of products with an offset""" topProducts(first: Int = 5): [Product] @deprecated(reason: "Use products instead") """Fetch a paginated list of products based on a filter type.""" products(first: Int = 5, after: Int = 0, type: ProductType): ProductConnection """ The currently authenticated user root. All nodes off of this root will be authenticated as the current user """ me: User }`;
new window.EmbeddedExplorer({
target: '#embeddableExplorer',
endpointUrl: 'https://acephei-gateway.herokuapp.com',
schema: getExampleSchema(),
initialState: {
variables: {
test: 'abcxyz',
},
displayOptions: {
showHeadersAndEnvVars: false,
},
},
});
```
--------------------------------
### Import Apollo Explorer and Sandbox (CommonJS)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Import patterns for Apollo Explorer and Apollo Sandbox using CommonJS module format.
```javascript
const { ApolloExplorer } = require('@apollo/explorer');
const { ApolloSandbox } = require('@apollo/sandbox');
const {
constructMultipartForm,
readMultipartWebStream,
} = require('@apollo/explorer-helpers');
```
--------------------------------
### Apollo Explorer - React Entry Point
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
The React-specific entry point for the Apollo Embeddable Explorer. Use this if you are working within a React application.
```APIDOC
## @apollo/explorer/react
### Description
Provides a React component for embedding the Apollo Explorer.
### Component
`ApolloExplorer`
### Props
- **`graphRef`** (string) - Required - The reference to the Apollo graph to load.
### Request Example
```javascript
import { ApolloExplorer } from '@apollo/explorer/react';
function MyApp() {
return ;
}
```
### Response
N/A (This is a React component.)
```
--------------------------------
### HandleRequest Type Definition
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/types.md
Function type for custom network request handlers. Allows intercepting, modifying, or delegating GraphQL requests. Use this to customize how requests are made, for example, by adding authorization headers.
```typescript
export type HandleRequest = (
endpointUrl: string,
options: Omit & { headers: Record }
) => Promise;
```
--------------------------------
### Import Apollo Explorer and Sandbox (ESM)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Import patterns for Apollo Explorer and Apollo Sandbox using ECMAScript Modules (ESM) format.
```javascript
import { ApolloExplorer } from '@apollo/explorer';
import { ApolloSandbox } from '@apollo/sandbox';
import {
constructMultipartForm,
readMultipartWebStream,
} from '@apollo/explorer-helpers';
```
--------------------------------
### Embedded Sandbox React Component Usage
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/EmbeddedSandbox.md
Shows how to integrate Apollo Sandbox into a React application using the provided React component. This example demonstrates passing initial endpoint and state, along with a CSS class for styling.
```typescript
import { ApolloSandbox } from '@apollo/sandbox/react';
function MyApp() {
return (
);
}
```
--------------------------------
### Import Apollo Explorer and Sandbox for React (TypeScript)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Import patterns for Apollo Explorer and Apollo Sandbox with type definitions for React applications using TypeScript.
```typescript
import { ApolloExplorer, type EmbeddableExplorerOptions } from '@apollo/explorer/react';
import { ApolloSandbox, type EmbeddableSandboxOptions } from '@apollo/sandbox/react';
```
--------------------------------
### Initialize Apollo Explorer
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/00_START_HERE.md
Instantiates the Apollo Explorer with a target DOM element and a graph reference. Ensure the target element exists in your HTML.
```typescript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@production',
});
```
--------------------------------
### Import Apollo Explorer and Sandbox for React
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Import patterns for Apollo Explorer and Apollo Sandbox specifically for React applications.
```typescript
import { ApolloExplorer } from '@apollo/explorer/react';
import { ApolloSandbox } from '@apollo/sandbox/react';
```
--------------------------------
### Initialize Apollo Sandbox (Vanilla JS)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/API_REFERENCE.md
Initializes the embeddable Apollo Sandbox using Vanilla JavaScript. Specify the target element and initial endpoint.
```typescript
import { ApolloSandbox } from '@apollo/sandbox';
const sandbox = new ApolloSandbox({
target: '#sandbox',
initialEndpoint: 'http://localhost:4000/graphql',
});
sandbox.dispose();
```
--------------------------------
### Explorer Cleanup and Disposal
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ARCHITECTURE.md
Explains the lifecycle of an Embedded Explorer instance, including the creation of an iframe and message listener, and their subsequent removal upon calling the `dispose()` method.
```text
new EmbeddedExplorer(options)
↓ creates
├─ iframe in DOM
└─ message listener via setupEmbedRelay()
↓
explorer.dispose()
├─ Removes iframe from DOM (via document.getElementById)
└─ Unregisters message listener (DisposableResource.dispose())
```
--------------------------------
### Apollo Sandbox Package Configuration
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Configuration for the @apollo/sandbox package, including name, version, main entry point, module entry point, typings, and exports.
```json
{
"name": "@apollo/sandbox",
"version": "2.7.4",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"typings": "dist/src/index.d.ts"
}
```
--------------------------------
### Initialize Apollo Explorer (Vanilla JS)
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/API_REFERENCE.md
Initializes the embeddable Apollo Explorer using Vanilla JavaScript. Specify the target element, graph reference, and initial state.
```typescript
import { ApolloExplorer } from '@apollo/explorer';
const explorer = new ApolloExplorer({
target: '#explorer',
graphRef: 'my-graph@production',
initialState: {
document: 'query { hello }',
},
});
// Cleanup
explorer.dispose();
```
--------------------------------
### Basic Sandbox Embedding with EmbeddedSandbox
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupSandboxEmbedRelay.md
Demonstrates basic embedding of the Sandbox iframe using the EmbeddedSandbox class. The setupSandboxEmbedRelay function is called internally by the constructor.
```typescript
import { EmbeddedSandbox } from '@apollo/sandbox';
const sandbox = new EmbeddedSandbox({
target: '#sandbox',
initialEndpoint: 'http://localhost:4000/graphql',
});
```
--------------------------------
### Apollo Explorer Package Configuration
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/packages.md
Configuration for the @apollo/explorer package, including name, version, main entry point, module entry point, typings, and exports.
```json
{
"name": "@apollo/explorer",
"version": "3.7.4",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"typings": "dist/src/index.d.ts",
"exports": {
"./react": { "import": "...", "require": "..." },
".": { "import": "...", "require": "..." }
}
}
```
--------------------------------
### Initialize Apollo Sandbox in Vanilla JS
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/sandbox/README.md
Instantiate the ApolloSandbox class, passing a CSS selector for the target HTML element where the sandbox will be embedded. Ensure the target element is styled appropriately.
```javascript
import { ApolloSandbox } from '@apollo/sandbox';
function App() {
...
new ApolloSandbox({
target: '#embeddableSandbox',
})
...
}
...
// style the iframe for your site
```
--------------------------------
### Query Execution Flow
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupSandboxEmbedRelay.md
Illustrates the message flow for executing a GraphQL query from the Sandbox, including dynamic endpoint usage.
```mermaid
graph TD
1[User types query in Sandbox and clicks execute]
2[Sandbox sends EXPLORER_QUERY_MUTATION_REQUEST]
3[setupSandboxEmbedRelay receives message]
4[Calls executeOperation()]
5[executeOperation() executes against provided endpoint]
6[Response sent back EXPLORER_QUERY_MUTATION_RESPONSE]
7[Sandbox renders results]
1 --> 2
2 --> 3
3 --> 4
4 --> 5
5 --> 6
6 --> 7
subgraph Message Details
2a(operationId: 'op-456')
2b(operation: 'query { users { id } }')
2c(variables: {})
2d(headers: { 'Authorization': 'Bearer ...' })
2e(endpointUrl: 'http://custom-endpoint:4000/graphql' (user can change))
2f(includeCookies: true)
end
subgraph executeOperation() Args
4a(Operation from message)
4b(Endpoint from message (user may have changed))
4c(handleRequest)
end
subgraph Response Details
6a(operationId: 'op-456')
6b(response: { data: {...}, status: 200, ... })
end
```
--------------------------------
### Advanced Custom Relay Control
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupSandboxEmbedRelay.md
Illustrates advanced usage where setupSandboxEmbedRelay is called directly to gain more control over the relay, including manual disposal.
```typescript
import { setupSandboxEmbedRelay } from '@apollo/sandbox';
const iframeEl = document.createElement('iframe');
iframeEl.src = 'https://sandbox.embed.apollographql.com/sandbox/explorer?endpoint=...';
document.body.appendChild(iframeEl);
const relay = setupSandboxEmbedRelay({
embeddedSandboxIFrameElement: iframeEl,
handleRequest: async (url, opts) => {
// Custom request handling
return fetch(url, opts);
},
__testLocal__: false,
});
// Later, clean up
relay.dispose();
```
--------------------------------
### Manual setupEmbedRelay Control
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupEmbedRelay.md
Illustrates advanced usage where setupEmbedRelay is called manually to control the postMessage relay. This includes creating an iframe, setting up the relay, and later disposing of it to clean up listeners.
```typescript
import { setupEmbedRelay } from '@apollo/explorer';
const iframeEl = document.createElement('iframe');
iframeEl.src = 'https://explorer.embed.apollographql.com?...';
document.body.appendChild(iframeEl);
const relay = setupEmbedRelay({
embeddedExplorerIFrameElement: iframeEl,
endpointUrl: 'http://localhost:4000/graphql',
handleRequest: fetch,
schema: mySchema,
updateSchemaInEmbed: (newSchema) => {
// Handle schema updates
},
graphRef: undefined,
autoInviteOptions: undefined,
__testLocal__: false,
});
// Later, clean up
relay.dispose();
```
--------------------------------
### executeSubscription
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/RequestExecution.md
Executes a subscription using WebSocket or multipart HTTP protocol. It handles the connection, subscription, and message streaming based on the specified protocol.
```APIDOC
## executeSubscription()
### Description
Executes a subscription using WebSocket or multipart HTTP protocol. It handles the connection, subscription, and message streaming based on the specified protocol.
### Method
`async function`
### Parameters
- **subscriptionUrl** (string) - WebSocket URL (e.g., `ws://...`) or HTTP endpoint
- **operation** (string) - The GraphQL subscription query.
- **operationName** (string | undefined) - The name of the subscription operation.
- **variables** (Record | undefined) - Variables for the subscription.
- **headers** (Record | undefined) - Custom headers for the request.
- **embeddedIFrameElement** (HTMLIFrameElement) - The iframe element hosting the embed.
- **operationId** (string) - A unique identifier for the operation.
- **embedUrlOrigin** (string) - The origin of the embed URL.
- **protocol** (GraphQLSubscriptionLibrary) - The subscription protocol to use: 'graphql-ws', 'subscriptions-transport-ws', or 'multipart-subscription'.
- **handleRequest** (HandleRequest) - A function to handle the actual HTTP request.
- **httpMultipartParams** ({includeCookies}) - Parameters for HTTP multipart subscriptions, including whether to include cookies.
### Returns
`Promise`
### Protocols Supported
1. **graphql-ws** — GraphQL WebSocket Protocol (graphql-ws library)
2. **subscriptions-transport-ws** — Legacy Apollo Subscriptions Protocol
3. **multipart-subscription** — HTTP multipart streaming (Apollo Router)
### WebSocket Protocol Flow
1. Creates subscription client based on protocol type
2. Opens WebSocket connection to subscriptionUrl
3. Subscribes to operation
4. On each message: sends postMessage to embed with response
5. On error/disconnect: sends error and status updates
6. Sends EXPLORER_SUBSCRIPTION_TERMINATION from embed to disconnect
### HTTP Multipart Flow
1. Sends subscription operation as POST request to HTTP endpoint
2. Streams multipart response using `readMultipartWebStream()`
3. Emits each chunk as separate postMessage
4. Handles connection termination per protocol
### Example
```typescript
// Executed when embed sends EXPLORER_SUBSCRIPTION_REQUEST
await executeSubscription({
subscriptionUrl: 'ws://localhost:4000/graphql',
operation: 'subscription OnMessage { messageAdded { text } }',
operationId: 'sub-456',
embeddedIFrameElement: iframeEl,
operationName: 'OnMessage',
variables: {},
headers: {},
embedUrlOrigin: 'https://explorer.embed.apollographql.com',
protocol: 'graphql-ws',
handleRequest: async (url, opts) => fetch(url, opts),
httpMultipartParams: { includeCookies: false },
});
```
```
--------------------------------
### Request Handling Flow
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ARCHITECTURE.md
Illustrates the flow of a request from the Explorer through the parent application to the target endpoint using a custom request handler.
```text
Explorer Parent Endpoint
│ │ │
│─ Request ─────────────→ │ handleRequest() │
│ ├──────────────────→ │
│ │ fetch(url, opts) │
│ │ ← Response │
│ ← Response ←────────────┤ │
│ │ │
```
--------------------------------
### Initialize Embeddable Apollo Sandbox
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/sandbox/src/examples/apollo-server.html
This JavaScript snippet initializes the embeddable Apollo Sandbox within an HTML element. It requires the `initialEndpoint` to be set to the server's URL.
```javascript
var initialEndpoint = window.location.href;
new window.EmbeddedSandbox({
target: '#embeddableSandbox',
initialEndpoint,
includeCookies: false,
});
```
--------------------------------
### Initialize Embedded Explorer with GraphRef
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/explorer/src/examples/graphRef.html
This snippet initializes the Embedded Explorer. Ensure the target DOM element exists before executing the script. It configures the explorer with a graph reference, endpoint, and initial state for a GraphQL query.
```javascript
new window.EmbeddedExplorer({
target: '#embeddableExplorer',
graphRef: 'acephei@current',
endpointUrl: 'https://acephei-gateway.herokuapp.com',
initialState: {
document: `query Example { me { id } }`,
variables: {
test: 'abcxyz',
},
displayOptions: {
showHeadersAndEnvVars: true,
},
},
});
```
--------------------------------
### Schema Polling Cycle
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupSandboxEmbedRelay.md
Describes the process for initial schema loading and subsequent polling for updates in the Sandbox.
```mermaid
graph TD
subgraph Initial Load
A[Sandbox sends INTROSPECTION_QUERY_WITH_HEADERS]
B[Relay executes and sends schema response]
C[Sandbox renders with initial schema]
end
subgraph Polling (every 5-30 seconds if pollForSchemaUpdates: true)
D[Sandbox sends INTROSPECTION_QUERY_WITH_HEADERS again]
E[Relay executes introspection]
F[If schema differs: Sandbox updates UI]
G[Repeat every poll interval]
end
A --> B --> C
C --> D
D --> E --> F --> G
```
--------------------------------
### Import Apollo Sandbox Components
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/sandbox/README.md
Import the ApolloSandbox class for vanilla JavaScript or the ApolloSandbox component for React applications from the @apollo/sandbox npm package.
```javascript
import { ApolloSandbox } from '@apollo/sandbox';
import { ApolloSandbox } from '@apollo/sandbox/react';
```
--------------------------------
### Initialize Embedded Sandbox for Local Development
Source: https://github.com/apollographql/embeddable-explorer/blob/main/packages/sandbox/src/examples/localDevelopmentExample.html
Instantiates the EmbeddedSandbox with a target DOM element and a local endpoint. Ensure the target DOM element exists before this script runs. The `__testLocal__: true` option is specific to local testing environments.
```javascript
new window.EmbeddedSandbox({ target: '#embeddableSandbox', initialEndpoint: 'http://localhost:3001',
__testLocal__: true, });
```
--------------------------------
### File Upload Handling
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/README.md
Explorer automatically handles file uploads via multipart forms. No explicit configuration is needed for basic multipart handling.
```typescript
const explorer = new ApolloExplorer({
target: '#explorer',
schema,
endpointUrl: 'http://localhost:4000/graphql',
// User can select files in the Explorer UI
// Automatically sent as multipart form data
});
```
--------------------------------
### setupEmbedRelay Function Signature
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/setupEmbedRelay.md
This is the function signature for setupEmbedRelay, outlining its parameters and return type. It's used to initialize the postMessage relay system for an embedded Explorer iframe.
```typescript
function setupEmbedRelay({
endpointUrl,
handleRequest,
embeddedExplorerIFrameElement,
updateSchemaInEmbed,
schema,
graphRef,
autoInviteOptions,
__testLocal__,
}: {
endpointUrl: string | undefined;
handleRequest: HandleRequest;
embeddedExplorerIFrameElement: HTMLIFrameElement;
updateSchemaInEmbed: (schema: string | IntrospectionQuery) => void;
schema?: string | IntrospectionQuery;
graphRef?: string;
autoInviteOptions?: { accountId: string; inviteToken: string };
__testLocal__: boolean;
}): DisposableResource
```
--------------------------------
### Dynamic Endpoint and Subscriptions in React
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloSandboxReact.md
Configure Apollo Sandbox with dynamic GraphQL and subscription endpoints using React state. This allows users to input and change endpoints at runtime.
```typescript
import { ApolloSandbox } from '@apollo/sandbox/react';
import { useState } from 'react';
function DynamicEndpointSandbox() {
const [endpoint, setEndpoint] = useState('http://localhost:4000/graphql');
const [subscriptionEndpoint, setSubscriptionEndpoint] = useState(
'ws://localhost:4000/graphql'
);
return (
);
}
```
--------------------------------
### Styling Apollo Sandbox with CSS Modules
Source: https://github.com/apollographql/embeddable-explorer/blob/main/_autodocs/ApolloSandboxReact.md
Integrate Apollo Sandbox with CSS Modules for scoped styling. Ensure the module is imported and the class name is correctly applied.
```typescript
import { ApolloSandbox } from '@apollo/sandbox/react';
import styles from './Sandbox.module.css';
```