Home

Awesome

pouch-redux-middleware

By Build Status

Redux Middleware for syncing state and a PouchDB database.

Propagates changes made to a state into PouchDB. Propagates changes made to PouchDB into the state.

Install

$ npm install pouch-redux-middleware --save

Overview

pouch-redux-middleware will automatically populate a part of the store, specified by path, with the documents using the specified actions. This "sub-state" will be a list of the documents straight out of the database. When the database is modified by a 3rd party (e.g. by replication) a Redux action will be dispatched to update the "sub-state". Conversely, if you alter a document within the "sub-state", then the document will be updated in the database.

Example

Example of configuring a store:

import * as types from '../constants/ActionTypes'
import PouchMiddleware from 'pouch-redux-middleware'
import { createStore, applyMiddleware } from 'redux'
import rootReducer from '../reducers'
import PouchDB from 'pouchdb'

export default function configureStore() {
  const db = new PouchDB('todos');

  const pouchMiddleware = PouchMiddleware({
    path: '/todos',
    db,
    actions: {
      remove: doc => { return { type: types.DELETE_TODO, id: doc._id } },
      insert: doc => { return { type: types.INSERT_TODO, todo: doc } },
      batchInsert: docs => { return { type: types.BATCH_INSERT_TODOS, todos: docs } }
      update: doc => { return { type: types.UPDATE_TODO, todo: doc } },
    }
  })

  const store = createStore(
    rootReducer,
    undefined,
    applyMiddleware(pouchMiddleware)
  )

  return store
}

API

PouchMiddleware(paths)

A path spec is an object describing the behaviour of a sub-tree of the state it has the following attributes:

Example of a path spec:

{
  path: '/todos',
  db,
  actions: {
    remove: doc => { return { type: types.DELETE_TODO, id: doc._id } },
    insert: doc => { return { type: types.INSERT_TODO, todo: doc } },
    batchInsert: docs => { return { type: types.BATCH_INSERT_TODOS, todos: docs } }
    update: doc => { return { type: types.UPDATE_TODO, todo: doc } },
  }
}

License

ISC