diffusion
Version:
Diffusion JavaScript client
79 lines (64 loc) • 2.3 kB
JavaScript
/*eslint valid-jsdoc: "off"*/
var Long = require('long');
var padding = "0000000000000000";
function SessionId(server, value) {
this.server = server;
this.value = value;
}
SessionId.prototype.toString = function() {
// It appears that converting back into strings requires unsigned longs
var server = padding + this.server.toUnsigned().toString(16);
var client = padding + this.value.toUnsigned().toString(16);
return (server.substr(server.length - 16) + '-' + client.substr(client.length - 16)).toLowerCase();
};
SessionId.prototype.toValue = function() {
return this.toString();
};
SessionId.fromString = function(str) {
var parts = str.split('-');
var sessionId;
try {
var server = Long.fromString(parts[0], false, 16);
var value = Long.fromString(parts[1], false, 16);
sessionId = new SessionId(server, value);
} catch (e) {
throw new Error('SessionId must consist of two hexadecimal parts, joined with a \'-\'');
}
return sessionId;
};
/**
* Determines if the provided SessionID is equal to this one.
*
* @param {SessionID} sessionid - The session id to compare with
* @returns {boolean} - False if the session id is not equal, True otherwise.
*/
SessionId.prototype.equals = function(sessionid) {
if (!(sessionid instanceof SessionId) ||
!(sessionid.server instanceof Long) ||
!(sessionid.value instanceof Long)) {
return false;
}
return this.server.compare(sessionid.server) === 0 &&
this.value.compare(sessionid.value) === 0;
};
/**
* Determines if a given string is a valid SessionID. If true, the returned value will be the parsed SessionID
*
* @param str {String} - The session id string
* @returns {boolean|SessionId} - False if the string cannot be parsed, or a constructed SessionID
*/
SessionId.validate = function(str) {
if (str instanceof SessionId) {
return str;
}
if (str.length === 0 || str.indexOf('-') < 0 || str.indexOf(' ') >= 0) {
return false;
}
try {
// Attempt to construct an actual session id; catch any errors thrown by the Long#fromString methods
return SessionId.fromString(str);
} catch (e) {
return false;
}
};
module.exports = SessionId;