Custom Scripts in the Explorer
Use pre- and postflight scripts to manage auth flows and test responses
The GraphOS Explorer can run custom scripts when executing each GraphQL operation, similar to tools like Postman. These JavaScript-based scripts can get and set the values of environment variables that the Explorer can then inject into HTTP header values or GraphQL variables.
Preflight scripts are useful for managing authentication flows like OAuth, for example, by refreshing an expired access token. Postflight scripts are useful for validating workflows that depend on response data.
Script types
The Explorer lets you define two different types of scripts:
Preflight scripts: You can define a single preflight script per variant of a graph. This script runs before every Explorer operation that's executed against the associated variant.
Preflight scripts are helpful for enabling organization-wide Explorer authentication to your graph.
Operation scripts: If you use operation collections, you can define one pre- and one post-operation script for each saved operation in a collection.
Pre-operation scripts run before the operation executes. They act as additional, per-operation, preflight scripts.
Post-operation scripts run after the operation executes. They act as per-operation postflight scripts.
Operation scripts are helpful for testing or debugging the behavior of individual operations or operation chains.
Script execution order
If you define and use all possible scripts for an operation, the order is as follows:
Important considerations for Explorer scripts
Scripts are stored in the Apollo cloud in plaintext.
cautionDo not include secret credentials in scripts. Instead, team members can provide their individual credentials to the Explorer via environment variables.If a team member has view access to a particular graph variant or operation collection, that team member can also view any scripts associated with that variant or operation collection.
Preflight scripts are on by default. Individual team members can turn them off for their own Explorer usage.
Operations scripts are off by default. Individual team members can turn them on for their own Explorer usage.
Preflight scripts
Add preflight scripts
To create a preflight script:
Open GraphOS Studio and then open the Explorer for the graph and variant you want to create a script for.
Open the Explorer's Settings tab and scroll down to the Preflight Script.
Click + Add script. A script editor dialog appears.
Click Show snippets on the bottom left of the editor to display a list of common helpful actions you can perform from your preflight script. Examples include sending HTTP requests and interacting with Explorer environment variables.
Develop your script in the Script editor panel. As you develop, you can click Test script to test its execution. Console messages are printed in the Console output panel.
When your script is ready, click Save. Studio stores your script.
That's it! After you save your script, it's automatically loaded for any team member that uses the Explorer with the associated variant.
Turn off preflight scripts
By default, a variant's preflight script runs automatically before every GraphQL operation that's executed in the Explorer. Team members can turn off the script for their individual Explorer usage from the Personal Settings > Scripts section of the Explorer's Settings tab. To do so, toggle the Preflight script switch to OFF.
Operation scripts
Add operation scripts
From the Explorer, open an operation from the Operation Collections menu:
From the Explorer's bottom panel, select the Pre-Operation Script or Post-Operation Script tab and click + Add Script. A script creation dialog appears.
Create, test, and save your script.
For details on script creation, see steps 4 and 5 of Add preflight scripts.
Click Test script to test your script before saving it.
After you save an operation script, make sure to turn it on so that it runs before or after its designated operation execution in the Explorer.
Mocking responses for post-operation scripts
The operation script modal has a Mocked Operation Response area so you can test post-operation scripts before saving them. Scripts can access any JSON GraphQL response you add in the Mocked Operation Response via the explorer.response.body
variable.
Turn on operation scripts
By default, operation scripts are off for each individual team member. Team members can turn on operation scripts for their individual Explorer usage from the Personal Settings > Scripts section of the Explorer's Settings tab. To do so, toggle the Operation script switch to ON.
Chaining operations
A script can use the explorer.runOperation
function to execute another operation that's saved in a collection. That operation might have its own script, which can also call explorer.runOperation
.
You can use this mechanism to chain together a sequence of operations for more advanced workflows.
Scripting API reference
These symbols are available within the scope of both preflight scripts and operation scripts. Snippets for these symbols are available via the Show snippets link in the scripting modal.
Name / Type |
Description |
---|---|
| Function that returns the current value of the environment variable with the specified key . |
| Function that sets a new value for the environment variable with the specified key . |
| Function for making HTTP requests to external services from within a script.Network requests are initiated from an origin of https://preflight-request.apollographql.com . Make sure the appropriate CORS headers are sent for those requests. |
| Function for executing other saved operations. If the target operation has defined its own script, it will run before its operation.
|
| Function that prompts the user for input and returns the value in a promise. If the user cancels the prompt, the promise resolves to null .The prompt supports Markdown rendering of the msg parameter. |
| Function that prompts the user to authenticate using your OAuth 2.0 provider's URL (specified by authUrl ). Provide any required query parameters to the auth endpoint via the queryParams parameter.This function returns a promise containing the query parameters from your OAuth provider's response. If the user cancels the prompt, the promise resolves to null .For OAuth 2.0 authentication to work with the Explorer, your OAuth 2.0 provider must recognize https://studio.apollographql.com/explorer-oauth2 as a valid redirect URL. You can configure this in your OAuth 2.0 provider settings when you set up a new client or application. |
| The body of the POST request that's sent to the configured GraphQL endpoint for the current operation. |
| The JSON representation of the GraphQL operation response. Used in post-operation scripts. |
| This exposes the crypto-js package for use within your script. For available functions, see the documentation. |
Examples
Get an environment variable
Scripts can access an environment variable set in the Explorer's settings like so:
1const secretToken = explorer.environment.get("token");
Set an environment variable
The following example runs an operation and sets an environment variable for use in future operations:
1const response = await explorer.runOperation({
2 scope: "shared",
3 graphRef: "SpaceX-pxxbxen@current",
4 collectionName: "Mission Control",
5 operationName: "Ships",
6});
7
8const firstShipID = response.result.data.ships[0].id;
9
10explorer.environment.set("shipID", firstShipID);
Authenticate using an authorization provider URL
The following example uses the explorer.oauth2Request
function to authenticate using an OAuth 2.0 provider's URL. View the function's reference for more details.
1const responseQueryParams = await explorer.oauth2Request(
2 'http://yourauthprovider.com/authorize',
3 {
4 client_id: "",
5 state: "",
6 scope: "openid",
7 response_type: "code",
8 code_challenge_method: "S256",
9 code_challenge: "",
10 code_verifier: "",
11 })
See the following example for how you can use the response from a explorer.oauth2Request
request to set an authorization environment variable.
Set an authorization environment variable
The following example uses the explorer.environment.set
function to set a date-based authorization token relying on the response of an Okta authorization request:
1let futureDate = explorer.environment.get('futureDate');
2const now = Date.now();
3if (!futureDate || now >= futureDate ) {
4
5 const authUrl = 'https://<customerdomain>.okta.com/oauth2/<customerid>/v1/authorize';
6 const qp = {
7 client_id: <clientid>,
8 state: "abc",
9 scope: "openid",
10 response_type: "token",
11 code_challenge_method: "S256",
12 nonce: "nonce"
13 };
14
15 const result = await explorer.oauth2Request(authUrl, qp);
16 const token = result.access_token;
17
18 explorer.environment.set('Authorization', {token});
19
20 const nowDate = new Date();
21 futureDate = new Date(nowDate.getTime() + (1 * 55 * 1000));
22 explorer.environment.set('futureDate', futureDate.getTime());
23
24}
Transform and log response data
You can use a post-operation script to filter, map, or otherwise transform response data and log it. This can be helpful when a request returns numerous results in the response.
For example, imagine you have a query called Ships
:
1query Ships {
2 id
3 name
4 model
5 manufacturer
6}
The corresponding response might look like this:
1{
2 "data": {
3 "Ships": [
4 {
5 "id": "1",
6 "name": "Millennium Falcon",
7 "model": "YT-1300 Light Freighter",
8 "manufacturer": "Corellian Engineering Corporation"
9 },
10 {
11 "id": "2",
12 "name": "X-wing Starfighter",
13 "model": "T-65 X-wing",
14 "manufacturer": "Incom Corporation"
15 }
16 // ... (thousands of ships)
17 ]
18 }
19}
You can use a post-operation script to access, transform, and log the returned results:
1 // Filter and map ships using some filtering and mapping functions
2function exampleTransform(ships, filterFn, mapFn) {
3 const filteredShips = ships.filter(filterFn);
4 const mappedShips = filteredShips.map(mapFn);
5 return mappedShips;
6}
7
8// Retrive and transform ships
9const allShips = explorer.response.body.data.Ships;
10const transformedShips = exampleTransform( allShips, filterFn, mapFn);
11
12// Log the result
13console.log(transformedShips);
You can view the logged results in the Console output section of the Explorer.
console.log
s in the Console output while writing and testing scripts. To see and interact with logged items when running an operation in Explorer, open your browser's devtools.