Skip to content
Andre Kless edited this page Apr 6, 2021 · 1 revision

If you use a ccmjs datastore and the data is managed in a server side database, you can use the websocket protocol and be notified from server when a dataset changes.

In the following example, the onchange function is called as soon as any dataset in the products collection changes:

const store = await ccm.store( {
  name: 'products',
  url: 'wss://server.side.de',
  onchange: dataset => {
    console.log( 'changed dataset:', dataset );
  }
} );

The dataset that has changed is passed to the onchange function. A web component can then specifically update its website area and users see the change in real time.

You can also only observe certain datasets in a collection. This is recommended to keep the traffic as small as possible. In the following example we only observes the dataset with the unique key foo:

const store = await ccm.store( {
  name: 'products',
  url: 'wss://server.side.de',
  observe: 'foo',
  onchange: dataset => {
    console.log( 'changed dataset:', dataset );
  }
} );

In the following example we only observe the datasets with the unique keys foo, bar and baz:

const store = await ccm.store( {
  name: 'products',
  url: 'wss://server.side.de',
  observe: [ 'foo', 'bar', 'baz' ],
  onchange: dataset => {
    console.log( 'changed dataset:', dataset );
  }
} );

It is also possible to only observe the datasets that match a specific query:

const store = await ccm.store( {
  name: 'products',
  url: 'wss://server.side.de',
  observe: { owner: 'john' },
  onchange: dataset => {
    console.log( 'changed dataset:', dataset );
  }
} );

We are only informed about changed datasets that have set the value John for the property owner.

In the last example we observe all datasets that match the query and the datasets with the unique keys foo, bar and baz:

const store = await ccm.store( {
  name: 'products',
  url: 'wss://server.side.de',
  observe: [ { owner: 'john' }, 'foo', 'bar', 'baz' ],
  onchange: dataset => {
    console.log( 'changed dataset:', dataset );
  }
} );