How to use sharedb - 10 common examples

To help you get started, we’ve selected a few sharedb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / sharedb / sharedb-tests.ts View on Github external
function startClient(callback) {
    const socket = new WebSocket('ws://localhost:8080');
    const connection = new ShareDBClient.Connection(socket);
    const doc = connection.get('examples', 'counter');
    doc.subscribe(() => {
        doc.submitOp([{p: ['numClicks'], na: 1}]);
        callback();
    });
    // sharedb-mongo query object
    connection.createSubscribeQuery('examples', {numClicks: {$gte: 5}}, null, (err, results) => {
        console.log(err, results);
    });
    // SQL-ish query adapter that takes a string query condition
    connection.createSubscribeQuery('examples', 'numClicks >= 5', null, (err, results) => {
        console.log(err, results);
    });
}
github chili-epfl / collab-react-components / src / server / CollabServer.js View on Github external
const server = http.createServer(app);
  let db = null;
  if (CollabServer.options.db.type === 'mongo') {
    db = CollabServer.options.db.url
      ? ShareDBMongo(CollabServer.options.db.url)
      : {};
    console.log('CollabServer: Using MongoDB adapter');
  } else {
    console.log(
      'CollabServer: No Database specified, falling back to In Memory'
    );
  }

  // Create the ShareDB backend (that will need to be exported)
  ShareDB.types.register(RichText.type);
  CollabServer.backend = new ShareDB({ db });

  // Create the Websocket server
  new WebSocket.Server({ server }).on('connection', function(ws) {
    CollabServer.backend.listen(new WebsocketJSONStream(ws));
    console.log('New socket client on CollabServer instance');
  });

  server.listen(CollabServer.options.port, function(err) {
    if (err) throw err;
    console.log(
      'CollabServer: Server listening on port ' + CollabServer.options.port
    );
  });
};
github usecanvas / realtime-v2 / sharedb / lib / sharedb-postgres-canvas.js View on Github external
'use strict';

/* eslint id-length: ["off"], newline-per-chained-call: ["off"] */

const Pg = require('pg');
const URL = require('url');
const ShareDBDB = require('sharedb').DB;

Pg.on('end', onPgEnd);

const pgPool = new Pg.Pool(parseDatabaseURL());

class ShareDBPGCanvas extends ShareDBDB {
  commit(orgID, canvasID, op, snapshot, options, cb) {
    return pgPool.connect().then(client => {
      return client.query('BEGIN').then(_ => {
        return this.doGetSnapshot(client, orgID, canvasID, [], options)
          .then(existingSnap => {
            if (snapshot.v !== existingSnap.v + 1) return false;
            return this.doCommit(client, canvasID, op, snapshot);
          }).then(success => {
            return client.query('COMMIT').then(_ => {
              return resolveQuery(success, cb, client);
github WinMinTun / sharedb-mysql / index.js View on Github external
console.log('Connection %d released', connection.threadId);
		});
			
		pool.on('enqueue', function () {
			console.log('Waiting for available connection slot');
		});
	}
	
	ops_table = options.ops_table ? options.ops_table : 'ops';
	snapshots_table = options.snapshots_table ? options.snapshots_table : 'snapshots';
	

};
module.exports = MySQLDB;

MySQLDB.prototype = Object.create(DB.prototype);

MySQLDB.prototype.close = function(callback) {
	this.closed = true;
	if (callback) callback();
};

function rollback(client, done) {
	client.query('ROLLBACK', function(err) {
		return done(err);
	})
}

// Persists an op and snapshot if it is for the next version. Calls back with
// callback(err, succeeded)
MySQLDB.prototype.commit = (collection, id, op, snapshot, options, callback) => {
github share / sharedb-mongo / index.js View on Github external
var id = conditions[i].d;
        var ops = opsBulk[id];
        var doc = docMap[id];
        var from = fromMap[id];
        var to = toMap && toMap[id];
        var filtered = filterOps(ops, doc, to);
        var err = checkOpsFrom(collectionName, id, filtered, from);
        if (err) return callback(err);
        opsMap[id] = filtered;
      }
      callback(null, opsMap);
    });
  });
};

DB.prototype.getCommittedOpVersion = function(collectionName, id, snapshot, op, callback) {
  var self = this;
  this.getOpCollection(collectionName, function(err, opCollection) {
    if (err) return callback(err);
    var query = {
      src: op.src,
      seq: op.seq
    };
    var projection = {v: 1, _id: 0};
    var sort = {v: 1};
    // Find the earliest version at which the op may have been committed.
    // Since ops are optimistically written prior to writing the snapshot, the
    // op could end up being written multiple times or have been written but
    // not count as committed if not backreferenced from the snapshot
    opCollection.find(query).project(projection).sort(sort).limit(1).next(function(err, doc) {
      if (err) return callback(err);
      // If we find no op with the same src and seq, we definitely don't have
github WinMinTun / sharedb-mysql / index.js View on Github external
function MySQLDB(options) {
	if (!(this instanceof MySQLDB)) return new MySQLDB(options);
	DB.call(this, options);

	this.closed = false;

	mysql_config = options.db;

	// connections in pool
	mysql_config.connectionLimit = options.db.connectionLimit ? options.connectionLimit : 10;
	  
	pool  = mysql.createPool(mysql_config);

	if (options.debug) {
		debug = options.debug;
		pool.on('acquire', function (connection) {
			console.log('Connection %d acquired', connection.threadId);
		});
github share / sharedb-redis-pubsub / index.js View on Github external
this.client = options.client || redis.createClient(options);

  // Redis doesn't allow the same connection to both listen to channels and do
  // operations. Make an extra redis connection for subscribing with the same
  // options if not provided
  this.observer = options.observer || redis.createClient(this.client.options);

  var pubsub = this;
  this.observer.on('message', function(channel, message) {
    var data = JSON.parse(message);
    pubsub._emit(channel, data);
  });
}
module.exports = RedisPubSub;

RedisPubSub.prototype = Object.create(PubSub.prototype);

RedisPubSub.prototype.close = function(callback) {
  if (!callback) {
    callback = function(err) {
      if (err) throw err;
    };
  }
  var pubsub = this;
  PubSub.prototype.close.call(this, function(err) {
    if (err) return callback(err);
    pubsub.client.quit(function(err) {
      if (err) return callback(err);
      pubsub.observer.quit(callback);
    });
  });
};
github chili-epfl / collab-react-components / src / server / CollabServer.js View on Github external
const server = http.createServer(app);
  let db = null;
  if (CollabServer.options.db.type === 'mongo') {
    db = CollabServer.options.db.url
      ? ShareDBMongo(CollabServer.options.db.url)
      : {};
    console.log('CollabServer: Using MongoDB adapter');
  } else {
    console.log(
      'CollabServer: No Database specified, falling back to In Memory'
    );
  }

  // Create the ShareDB backend (that will need to be exported)
  ShareDB.types.register(RichText.type);
  CollabServer.backend = new ShareDB({ db });

  // Create the Websocket server
  new WebSocket.Server({ server }).on('connection', function(ws) {
    CollabServer.backend.listen(new WebsocketJSONStream(ws));
    console.log('New socket client on CollabServer instance');
  });

  server.listen(CollabServer.options.port, function(err) {
    if (err) throw err;
    console.log(
      'CollabServer: Server listening on port ' + CollabServer.options.port
    );
  });
};
github share / sharedb-redis-pubsub / index.js View on Github external
function RedisPubSub(options) {
  if (!(this instanceof RedisPubSub)) return new RedisPubSub(options);
  PubSub.call(this, options);
  options || (options = {});

  this.client = options.client || redis.createClient(options);

  // Redis doesn't allow the same connection to both listen to channels and do
  // operations. Make an extra redis connection for subscribing with the same
  // options if not provided
  this.observer = options.observer || redis.createClient(this.client.options);

  var pubsub = this;
  this.observer.on('message', function(channel, message) {
    var data = JSON.parse(message);
    pubsub._emit(channel, data);
  });
}
module.exports = RedisPubSub;
github Webstrates / Webstrates / helpers / ShareDBWrapper.js View on Github external
module.exports.submitOp = (webstrateId, op, next) => {
	// https://github.com/share/sharedb/blob/master/lib/backend.js
	// Maybe this method is unnecessary and could be replaced by just submit. But that will
	// trigger the submit event, this won't, so I don't know.
	const request = new sharedb.SubmitRequest(share, agent, COLLECTION_NAME, webstrateId, op);
	request.submit(next);
};