• Docs
  • Pricing
  • Support
  • Blog
  • Login

›Advanced

Intro

  • What's OneGraph?
  • How does it work?
  • Creating your first app
  • Making your first query
  • OneGraphiQL
  • Authentication & Security Overview
  • Custom Google Auth

On the frontend

  • Using with Apollo
  • Log in to services
  • Example with create-react-app

External Authentication

  • What are JWTs?
  • AuthGuardian
  • Securing your Apollo server
  • Securing your Hasura API
  • Securing your Netlify site
  • Securing your express.js app
  • Advanced JWT customization with webhooks

Subscriptions

  • Subscriptions
  • Webhook-based subscriptions
  • Websocket-based subscriptions
  • Salesforce subscriptions
  • GitHub subscriptions
  • Gmail Subscriptions

Advanced

  • Persisted Queries
  • Mailchimp Signup with Persisted Queries

Mailchimp Signup with Persisted Queries

This example will show you how to create a Mailchimp mailing list signup form with a persisted query on OneGraph.

You can embed the signup form on any static HTML page--no server required!

You'll need a Mailchimp account and a OneGraph app.

The end result will be similar to the signup form on the OneGraph changelog.

Mailchimp signup form

First, create a new OneGraph app or use an existing app on the OneGraph dashboard.

Create an auth token

The first step is to create an auth token on OneGraph with access to your Mailchimp account. The query we're going to build will allow public users restricted access to your auth. You can think of it like building a custom API endpoint, but you never have to set up a server or store API tokens.

Set up the auth.

Go to the Server-side Auth pane on the OneGraph dashboard

Server-side Auth pane

Click "Create Token" and add Mailchimp

Server-side Auth create token

Create the persisted query

Go to the Persisted queries tab on the dashboard and scroll down to create a new query.

Enter the following query, but replace your mailing list id in the path param. You can use this query to list all of your mailing lists: https://www.onegraph.com/graphiql?shortenedId=538JEM

mutation MailchimpSignup($email: String!, $firstName: String!, $lastName: String!) {
  mailchimp {
    makeRestCall {
      post(
        path: "/3.0/lists/e6680e715f/members"
        jsonBody: {
          email_address: $email
          status: "pending"
          merge_fields: {
            FNAME: $firstName
            LNAME: $lastName
          }
        }
      ) {
        jsonBody
      }
    }
  }
}

Persisted query form

Make sure to set the query to use your new "mailchimp-signup" auth token and add email, firstName, and lastName to the list of free variables.

Free variables are the only query variables that can be provided by the caller of the query. For this query, we only want a user to be able to subscribe to a pre-defined mailing list. By limiting the free variables, we prevent the user from performing arbirtrary actions.

Click "Create Persisted Query" and copy the doc id. In my case it's 927bcb5d-1681-4c3e-891a-986baa48fd93.

Create the form

Now that we have the query, we can build our form.

First, we'll write a javascript function that sends the query to the server:

// Replace with your app id
const ONE_GRAPH_APP_ID = 'b37c8c80-650b-4052-93d2-e100236a5298';
// Replace with the doc id you created
const DOC_ID = '927bcb5d-1681-4c3e-891a-986baa48fd93';

function subscribe({firstName, lastName, email}) {
  // Posts the GraphQL query to onegraph
  return fetch(
    'https://serve.onegraph.com/graphql?app_id=' + ONE_GRAPH_APP_ID,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'applcation/json',
      },
      // doc_id and variables should be in the JSON-encoded body
      body: JSON.stringify({
        doc_id: DOC_ID,
        variables: {
          firstName,
          lastName,
          email,
        },
      }),
    },
  ).then((res) =>
    res.json().then((json) => {
      // Catch any errors
      if (json.errors) {
        throw new Error(json.errors[0].message);
      } else {
        const body = json.data.mailchimp.makeRestCall.post.jsonBody;
        if (!body.email_address) {
          if (body.errors) {
            // Requires some knowledge of Mailchimp's API response format
            // This will improve as OneGraph continues to build out the Mailchimp API
            throw new Error(
              body.errors.find((e) => e.field === 'email_address')
                ? 'Invalid email'
                : 'Unknown error',
            );
          }
          if (body.detail) {
            throw new Error(body.detail);
          }
          throw new Error('Unknown error');
        }
      }
    }),
  );
}

Now we'll hook it up to our component (view on codesandbox)

import React from 'react';
import ReactDOM from 'react-dom';

import './styles.css';

// Replace with your app id
const ONE_GRAPH_APP_ID = 'b37c8c80-650b-4052-93d2-e100236a5298';
// Replace with the doc id you created
const DOC_ID = '927bcb5d-1681-4c3e-891a-986baa48fd93';

function App() {
  const [fields, setfields] = React.useState({
    firstName: '',
    lastName: '',
    email: '',
  });
  const [success, setSuccess] = React.useState(false);
  const [error, setError] = React.useState(null);
  if (success) {
    return <p>Subscribed! Check your email to confirm.</p>;
  }
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        setError(null);
        subscribe({
          firstName: fields.firstName,
          lastName: fields.lastName,
          email: fields.email,
        })
          .then((res) => {
            setSuccess(true);
          })
          .catch((e) => setError(e.message));
      }}>
      <input
        type="text"
        value={fields.firstName}
        onChange={(e) => setfields({...fields, firstName: e.target.value})}
        placeholder="First name"
      />
      <input
        type="text"
        value={fields.lastName}
        onChange={(e) => setfields({...fields, lastName: e.target.value})}
        placeholder="Last name"
      />

      <input
        type="text"
        value={fields.email}
        onChange={(e) => setfields({...fields, email: e.target.value})}
        placeholder="Email address"
      />
      {error ? <p>{error}</p> : null}
      <input type="submit" value="Subscribe" />
    </form>
  );
}

function subscribe({firstName, lastName, email}) {
  // Posts the GraphQL query to onegraph
  return fetch(
    'https://serve.onegraph.com/graphql?app_id=' + ONE_GRAPH_APP_ID,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'applcation/json',
      },
      // doc_id and variables should be in the JSON-encoded body
      body: JSON.stringify({
        doc_id: DOC_ID,
        variables: {
          firstName,
          lastName,
          email,
        },
      }),
    },
  ).then((res) =>
    res.json().then((json) => {
      // Catch any errors
      if (json.errors) {
        throw new Error(json.errors[0].message);
      } else {
        const body = json.data.mailchimp.makeRestCall.post.jsonBody;
        if (!body.email_address) {
          if (body.errors) {
            // Requires some knowledge of Mailchimp's API response format
            // This will improve as OneGraph continues to build out the Mailchimp API
            throw new Error(
              body.errors.find((e) => e.field === 'email_address')
                ? 'Invalid email'
                : 'Unknown error',
            );
          }
          if (body.detail) {
            throw new Error(body.detail);
          }
          throw new Error('Unknown error');
        }
      }
    }),
  );
}
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

You can see the full example working in the code sandbox embedded below.


This example uses React, but the same subscribe function could be used with Angular, Vue, Next.js, Gatsby, or even plain HTML.

← Persisted Queries
Links
OneGraph Overview Example projectsOneGraphiQL Explorer
Support
Live chat on Spectrum> TwitterBlog
More
Terms of ServicePrivacy Policy
Copyright © 2021 OneGraph