Skip to content

Commit

Permalink
Move snapshot building function into ot
Browse files Browse the repository at this point in the history
The function for building a snapshot from ops is useful, and has no
dependencies on `Backend`. This change moves it into the `ot` module,
where it will be a bit more discoverable and can be reused.
  • Loading branch information
Alec Gibson committed Jan 23, 2019
1 parent 579b22c commit 8e46271
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 32 deletions.
35 changes: 3 additions & 32 deletions lib/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -709,38 +709,9 @@ Backend.prototype._fetchSnapshotByTimestamp = function (collection, id, timestam
};

Backend.prototype._buildSnapshotFromOps = function (id, startingSnapshot, ops, callback) {
var type = null;
var data;
var fetchedVersion = 0;

if (startingSnapshot) {
type = types.map[startingSnapshot.type];
if (!type) return callback({ code: 4008, message: 'Unknown type' });
data = startingSnapshot.data;
fetchedVersion = startingSnapshot.v;
}

for (var index = 0; index < ops.length; index++) {
var op = ops[index];

fetchedVersion = op.v + 1;

if (op.create) {
type = types.map[op.create.type];
if (!type) return callback({ code: 4008, message: 'Unknown type' });
data = type.create(op.create.data);
} else if (op.del) {
data = undefined;
type = null;
} else {
data = type.apply(data, op.op);
}
}

type = type ? type.uri : null;

var snapshot = new Snapshot(id, fetchedVersion, type, data, null);
callback(null, snapshot);
var snapshot = startingSnapshot || new Snapshot(id, 0, null, undefined, null);
var error = ot.applyOps(snapshot, ops);
callback(error, snapshot);
};

function pluckIds(snapshots) {
Expand Down
35 changes: 35 additions & 0 deletions lib/ot.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,38 @@ exports.transform = function(type, op, appliedOp) {

if (op.v != null) op.v++;
};

/**
* Apply an array of ops to the provided snapshot.
*
* @param snapshot - a Snapshot object which will be mutated by the provided ops
* @param ops - an array of ops to apply to the snapshot
* @returns an error object if applicable
*/
exports.applyOps = function (snapshot, ops) {
var type = null;

if (snapshot.type) {
type = types[snapshot.type];
if (!type) return { code: 4008, message: 'Unknown type' };
}

for (var index = 0; index < ops.length; index++) {
var op = ops[index];

snapshot.v = op.v + 1;

if (op.create) {
type = types[op.create.type];
if (!type) return { code: 4008, message: 'Unknown type' };
snapshot.data = type.create(op.create.data);
snapshot.type = type.uri;
} else if (op.del) {
snapshot.data = undefined;
type = null;
snapshot.type = null;
} else {
snapshot.data = type.apply(snapshot.data, op.op);
}
}
};

0 comments on commit 8e46271

Please sign in to comment.