diffusion
Version:
Diffusion JavaScript client
83 lines (61 loc) • 2.09 kB
JavaScript
var _implements = require('util/interface')._implements;
var BytesImpl = require('data/bytes-impl');
var BinaryDeltaTypeImpl = require('data/binary/binary-delta-type-impl');
var JSONDeltaImpl = require('data/json/json-delta-impl');
var Int64Impl = require('data/primitive/int64-impl');
var JSONType = require('../../../data/json/json');
var identity = require('util/function').identity;
var Encoder = require('cbor/encoder');
var Decoder = require('cbor/decoder');
var encoder = new Encoder();
var BINARY_DELTA_TYPE = new BinaryDeltaTypeImpl(JSONImpl, from, identity);
function from(value) {
if (value instanceof JSONImpl) {
return value;
} else {
return new JSONImpl(encoder.encode(value).flush());
}
}
function int64Replacer(key, value) {
if (Int64Impl.isPrototypeOf(value)) {
return value.toString();
}
return value;
}
function JSONImpl(buffer, offset, length) {
// eslint-disable-next-line no-underscore-dangle
BytesImpl.__constructor.call(this, buffer, offset, length);
var self = this;
this.get = function() {
var decoder = new Decoder(buffer, offset, length);
return decoder.nextValue();
};
this.diff = function(original, type) {
var binaryDiff = self.binaryDiff(original);
if (type === "json") {
return new JSONDeltaImpl(JSONImpl, original, self, binaryDiff);
} else {
return binaryDiff;
}
};
this.binaryDiff = function(original) {
return BINARY_DELTA_TYPE.diff(original, self);
};
this.jsonDiff = function(original) {
return self.diff(original, "json");
};
this.apply = function(delta) {
return BINARY_DELTA_TYPE.apply(self, delta);
};
this.toString = function() {
return JSON.stringify(self.get());
};
this.toJsonString = function() {
return JSON.stringify(self.get(), int64Replacer);
};
}
module.exports = _implements(JSONType, JSONImpl);
module.exports.from = from;
module.exports.toString = function() {
return "JSONImpl";
};