diffusion
Version:
Diffusion JavaScript client
91 lines (79 loc) • 3.31 kB
JavaScript
var UpdateStream = require('topic-update/update-stream');
var NewUpdateStream = require('topic-update/new-update-stream');
var NewAddTopicAndUpdateStream = require('topic-update/new-add-topic-and-update-stream');
var TopicType = require('../../topics/topics').TopicType;
var requireNonNull = require('util/require-non-null');
var UpdateStreamFactory = function(streamServices) {
var getValueCheckOperation = function(dataType) {
if (['int64', 'double', 'string'].includes(dataType.name())) {
return function() {};
}
else {
return function(value) {
requireNonNull(value, "null can only be passed for int64, double or string topics");
};
}
};
var getChangeService = function(deltaType) {
return (deltaType === undefined)?
streamServices.STREAM_SET_TOPIC_SERVICE:
streamServices.STREAM_APPLY_DELTA_SERVICE;
};
var getToBytesFunction = function(dataType, deltaType) {
if (deltaType === undefined) {
return function(oldValue, newValue) {
return dataType.from(newValue).asBuffer();
};
}
else {
return function(oldValue, newValue) {
var delta = deltaType.diff(oldValue, newValue);
return delta.$buffer.slice(delta.$offset, delta.$offset + delta.$length);
};
}
};
var binaryDeltaType = function(dataType) {
try {
return dataType.binaryDeltaType();
}
catch (e) {
// catch the error and return undefined to signal that no delta type is available
return;
}
};
this.createUpdateStream = function(path, dataType, constraint) {
var deltaType = binaryDeltaType(dataType);
var options = {
dataType: dataType,
checkOperation: getValueCheckOperation(dataType),
toBuffer: getToBytesFunction(dataType, deltaType),
deltaService: getChangeService(deltaType)
};
var topicType = TopicType[dataType.name().toUpperCase()];
return new UpdateStream(
function(updateStreamImpl) {
return new NewUpdateStream(streamServices, options, updateStreamImpl, path, topicType, constraint);
}
);
};
this.createUpdateStreamThatAddsTopic = function(path, specification, dataType, constraint) {
var deltaType = binaryDeltaType(dataType);
var options = {
dataType: dataType,
checkOperation: getValueCheckOperation(dataType),
toBuffer: getToBytesFunction(dataType, deltaType),
deltaService: getChangeService(deltaType)
};
return new UpdateStream(
function(updateStreamImpl) {
return new NewAddTopicAndUpdateStream(streamServices,
options,
updateStreamImpl,
path,
specification,
constraint);
}
);
};
};
module.exports = UpdateStreamFactory;