Cozy Realtime

npm version license travis npm downloads david-dm david-dm renovate


What’s cozy-realtime?

A simple way to have realtime using Websocket with cozy-stack.

Setup

Install

npm install --save cozy-realtime or yarn add cozy-realtime

API

subscribe(config, doctype, options)

This method allow you to subscribe to realtime for one document or all documents of a provided doctype. Here are the parameters:

It will return a subscription object with onCreate (except if subscribing on specific document), onUpdate and onDelete methods.

Here is an example:

import realtime from 'cozy-realtime'

const config = {
    token: authToken, // app token provided by the stack or the client
    domain: 'cozy.tools:8080',
    secure: true // to use wss (with SSL) or not
  }
const subscription = realtime.subscribe(config, 'io.mocks.mydocs')

// your code when a new document is created
subscription.onCreate(doc => doSomethingOnCreate(doc))
// your code when a document is updated
subscription.onUpdate(doc => doSomethingOnUpdate(doc))
// your code when a document is deleted
subscription.onDelete(doc => doSomethingOnDelete(doc))

// Unsubscribe all events from realtime
subscription.unsubscribe()

// for a specific document
const docSubscription = realtime.subscribe(config, 'io.mocks.mydocs')

// There is no onCreate here since to have the id,
// the document is already created

// your code when your document is updated
docSubscription.onUpdate(doc => doSomethingOnUpdate(doc))
// your code when your document is deleted
docSubscription.onDelete(doc => doSomethingOnDelete(doc))

// Unsubscribe all events from realtime
docSubscription.unsubscribe()

All onCreate, onUpdate and onDelete methods will return the subscription so you can chain the call like below:

import realtime from 'cozy-realtime'

const config = {
    token: authToken, // app token provided by the stack or the client
    domain: 'cozy.tools:8080',
    secure: true // to use wss (with SSL) or not
  }
const subscription = realtime.subscribe(config, 'io.mocks.mydocs')
  // your code when a new document is created
  .onCreate(doc => doSomethingOnCreate(doc))
  // your code when a document is updated
  .onUpdate(doc => doSomethingOnUpdate(doc))
  // your code when a document is deleted
  .onDelete(doc => doSomethingOnDelete(doc))

// Unsubscribe all events from realtime
subscription.unsubscribe()

Maintainers

The maintainers for Cozy Realtime are Greg and CPatchane !

License

cozy-realtime is distributed under the MIT license.