0.1.1 • Published 5 years ago

apollo-link-pouchdb v0.1.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

Take a look at banner, Michael

apollo-link-pouchdb

A simple apollo-link to help you query a local PouchDB database with GraphQL enabling fast, robust, offline-first mobile and web applications.


Quick Start

First, you'll need to get apollo-client, apollo-link, apollo-link-pouchdb, and pouchdb installed:

npm install apollo-link apollo-link-pouchdb pouchdb --save

Now that the dependencies are installed, lets gets ApolloLink configured:

import { ApolloClient } from 'apollo-client'
import { ApolloLink } from 'apollo-link'
import withPouchDB from 'apollo-link-pouchdb'
import PouchDB from 'pouchdb'

// Create a PouchDB databsed called "example" or connect to it if it already exists.
const database = new PouchDB('example')

// Create and configure an Apollo Client
const client = ApolloClient({
  link: ApolloLink.from([withPouchDB({ database })]),
})

At this point, client can be sent to something like ApolloProvider from react-apollo, but its not very useful yet. We need to tell Apollo how to query PouchDB data and to do that we'll setup a resolver and then pass it to our client:

// Create a resolver for returning all documents in the database. Assume that we have documents stored
// in our database that look like this: `{ id: "1234", title: "A Title", content: "Some Content" }.
const resolvers = {
  Query: {
    documents: async (_root, _args, context, _info) => {
      try {
        const { rows } = await context.database.allDocs({ include_docs: true })
        return rows.map(({ doc, key }) => ({ ...doc, _id: key, __typename: 'Document' }))
      } catch (error) {
        console.error('PouchDB Error', error)
        return null
      }
    },
  },
}

// Create and configure an Apollo Client
const client = ApolloClient({
  link: ApolloLink.from([withPouchDB({ database, resolvers })]),
})

Now we'll be able to query the documents with GraphQL:

query GetDocuments {
  documents {
    id
    title
    content
  }
}

What is PouchDB?

Documentation

Using PouchDB with React Native

Local Development