@grafbase/apollo-link
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

@grafbase/apollo-link

Apollo-link for handling Server Sent Events (SSE)

Getting Started

Follow these steps in a new or existing React application

  1. Install the dependencies
npm install @apollo/client graphql @grafbase/apollo-link
  1. Initialize ApolloClient
// client.ts
import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client'

const initializeApolloClient = (link: ApolloLink) => {
  return new ApolloClient({
    cache: new InMemoryCache(),
    link: link
  })
}
  1. Create ApolloLink
// client.ts
import { HttpLink, split } from '@apollo/client'
import { getOperationAST } from 'graphql'
import { isLiveQuery, SSELink } from '@grafbase/apollo-link'

// Token generated by your auth provider: https://grafbase.com/docs/reference/directives#auth
const token = '....'

export const createApolloLink = () => {
  const sseLink = new SSELink({
    uri: process.env.GRAFBASE_API_URL,
    headers: {
      authorization: `Bearer ${token}`
    }
  })

  const httpLink = new HttpLink({
    uri: process.env.GRAFBASE_API_URL,
    headers: {
      authorization: `Bearer ${token}`
    }
  })

  return split(
    ({ query, operationName, variables }) =>
      isLiveQuery(getOperationAST(query, operationName), variables),
    sseLink,
    httpLink
  )
}
  1. Connect ApolloClient to React
// index.ts
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { ApolloProvider } from '@apollo/client'
import { initializeApolloClient } from './client'

const client = initializeApolloClient(createApolloLink())

ReactDOM.createRoot(document.getElementById('root')).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
)
  1. Subscribe to data changes
// App.tsx
import { gql, useQuery } from '@apollo/client'

const QUERY = gql`
  query @live {
    todoListCollection(first: 5) {
      edges {
        node {
          id
          title
        }
      }
    }
  }
`

function App() {
  const { loading, error, data } = useQuery(QUERY)

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error : {error.message}</p>

  return (
    <>
      {data?.todoListCollection?.edges?.map(
        ({ node: { id, title } }: { node: { id: string; title: string } }) => (
          <div key={id}>
            <div>{title}</div>
          </div>
        )
      )}
    </>
  )
}

export default App

Readme

Keywords

none

Package Sidebar

Install

npm i @grafbase/apollo-link

Weekly Downloads

40

Version

1.1.0

License

MIT

Unpacked Size

20.3 kB

Total Files

6

Last publish

Collaborators

  • pimeys
  • grafbase-ci
  • yoav-lavi-grafbase
  • fbjork