THRIFT-5811: Update eslint & prettier
Client: js
Patch: Cameron Martin
This closes #3087
diff --git a/lib/js/Gruntfile.js b/lib/js/Gruntfile.js
index 9771314..089ef8f 100644
--- a/lib/js/Gruntfile.js
+++ b/lib/js/Gruntfile.js
@@ -5,47 +5,48 @@
// Grunt Setup - npm install //reads the ./package.json and installs project dependencies
// Run grunt - npx grunt // uses project-local installed version of grunt (from package.json)
-module.exports = function(grunt) {
- 'use strict';
+module.exports = function (grunt) {
+ "use strict";
grunt.initConfig({
- pkg: grunt.file.readJSON('package.json'),
+ pkg: grunt.file.readJSON("package.json"),
concat: {
options: {
- separator: ';'
+ separator: ";",
},
dist: {
- src: ['src/**/*.js'],
- dest: 'dist/<%= pkg.name %>.js'
- }
+ src: ["src/**/*.js"],
+ dest: "dist/<%= pkg.name %>.js",
+ },
},
- jsdoc : {
- dist : {
- src: ['src/*.js', './README.md'],
- options: {
- destination: 'doc'
- }
- }
+ jsdoc: {
+ dist: {
+ src: ["src/*.js", "./README.md"],
+ options: {
+ destination: "doc",
+ },
+ },
},
uglify: {
options: {
- banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
+ banner:
+ '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n',
},
dist: {
files: {
- 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
- }
- }
+ "dist/<%= pkg.name %>.min.js": ["<%= concat.dist.dest %>"],
+ },
+ },
},
shell: {
InstallThriftJS: {
- command: 'cp src/thrift.js test/build/js/thrift.js'
+ command: "cp src/thrift.js test/build/js/thrift.js",
},
InstallThriftNodeJSDep: {
- command: 'cd ../.. && npm install'
+ command: "cd ../.. && npm install",
},
InstallTestLibs: {
- command: 'cd test && ant download_jslibs'
+ command: "cd test && ant download_jslibs",
},
ThriftGen: {
command: [
@@ -55,34 +56,38 @@
'"../../compiler/cpp/thrift" -gen js:node --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift',
'"../../compiler/cpp/thrift" -gen js:es6 --out test/gen-js-es6 ../../test/v0.16/ThriftTest.thrift',
'"../../compiler/cpp/thrift" -gen js:node,es6 --out ./test/gen-nodejs-es6 ../../test/v0.16/ThriftTest.thrift',
- ].join(' && ')
+ ].join(" && "),
},
ThriftGenJQ: {
- command: '../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/v0.16/ThriftTest.thrift'
+ command:
+ "../../compiler/cpp/thrift -gen js:jquery -gen js:node -o test ../../test/v0.16/ThriftTest.thrift",
},
ThriftGenDeepConstructor: {
- command: '../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift'
+ command:
+ "../../compiler/cpp/thrift -gen js -o test ../../test/JsDeepConstructorTest.thrift",
},
ThriftBrowserifyNodeInt64: {
command: [
- './node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js',
- './node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js',
- './node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js'
- ].join(' && ')
+ "./node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js",
+ "./node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js",
+ "./node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js",
+ ].join(" && "),
},
ThriftGenInt64: {
- command: '../../compiler/cpp/thrift -gen js -o test ../../test/Int64Test.thrift'
+ command:
+ "../../compiler/cpp/thrift -gen js -o test ../../test/Int64Test.thrift",
},
ThriftGenDoubleConstants: {
- command: '../../compiler/cpp/thrift -gen js -o test ../../test/DoubleConstantsTest.thrift'
+ command:
+ "../../compiler/cpp/thrift -gen js -o test ../../test/DoubleConstantsTest.thrift",
},
ThriftTestServer: {
options: {
async: true,
execOptions: {
cwd: "./test",
- env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
- }
+ env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" },
+ },
},
command: "node server_http.js",
},
@@ -91,8 +96,8 @@
async: true,
execOptions: {
cwd: "./test",
- env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
- }
+ env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" },
+ },
},
command: "node server_http.js --es6",
},
@@ -101,8 +106,8 @@
async: true,
execOptions: {
cwd: "./test",
- env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
- }
+ env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" },
+ },
},
command: "node server_https.js",
},
@@ -111,8 +116,8 @@
async: true,
execOptions: {
cwd: "./test",
- env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
- }
+ env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" },
+ },
},
command: "node server_https.js --es6",
},
@@ -120,213 +125,201 @@
qunit: {
ThriftJS: {
options: {
- urls: [
- 'http://localhost:8089/test-nojq.html'
- ],
+ urls: ["http://localhost:8089/test-nojq.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
+ },
},
ThriftJSJQ: {
options: {
- urls: [
- 'http://localhost:8089/test.html'
- ],
+ urls: ["http://localhost:8089/test.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
+ },
},
ThriftJS_DoubleRendering: {
options: {
- urls: [
- 'http://localhost:8089/test-double-rendering.html'
- ],
+ urls: ["http://localhost:8089/test-double-rendering.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
ThriftJS_Int64: {
options: {
- urls: [
- 'http://localhost:8089/test-int64.html'
- ],
+ urls: ["http://localhost:8089/test-int64.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
ThriftWS: {
options: {
- urls: [
- 'http://localhost:8089/testws.html'
- ],
+ urls: ["http://localhost:8089/testws.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
+ },
},
ThriftJS_TLS: {
options: {
- urls: [
- 'https://localhost:8091/test-nojq.html'
- ],
+ urls: ["https://localhost:8091/test-nojq.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
ThriftJSJQ_TLS: {
options: {
- urls: [
- 'https://localhost:8091/test.html'
- ],
+ urls: ["https://localhost:8091/test.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
ThriftWS_TLS: {
options: {
- urls: [
- 'https://localhost:8091/testws.html'
- ],
+ urls: ["https://localhost:8091/testws.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
ThriftDeepConstructor: {
options: {
- urls: [
- 'http://localhost:8089/test-deep-constructor.html'
- ],
+ urls: ["http://localhost:8089/test-deep-constructor.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
+ },
},
ThriftWSES6: {
options: {
- urls: [
- 'http://localhost:8088/test-es6.html'
- ],
+ urls: ["http://localhost:8088/test-es6.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
- }
+ },
+ },
},
jshint: {
// The main Thrift library file. not es6 yet :(
lib: {
- src: ['src/**/*.js'],
+ src: ["src/**/*.js"],
},
// The test files use es6
test: {
- src: ['Gruntfile.js', 'test/*.js'],
+ src: ["Gruntfile.js", "test/*.js"],
options: {
esversion: 6,
- }
+ },
},
gen_js_code: {
- src: ['test/gen-js/*.js', 'test/gen-js-jquery/*.js'],
+ src: ["test/gen-js/*.js", "test/gen-js-jquery/*.js"],
},
gen_es6_code: {
- src: ['test/gen-js-es6/*.js'],
+ src: ["test/gen-js-es6/*.js"],
options: {
esversion: 6,
- }
+ },
},
gen_node_code: {
- src: ['test/gen-nodejs/*.js'],
+ src: ["test/gen-nodejs/*.js"],
options: {
node: true,
- }
+ },
},
gen_node_es6_code: {
- src: ['test/gen-nodejs-es6/*.js'],
+ src: ["test/gen-nodejs-es6/*.js"],
options: {
node: true,
esversion: 6,
- }
- }
+ },
+ },
},
});
- grunt.loadNpmTasks('grunt-contrib-uglify');
- grunt.loadNpmTasks('grunt-contrib-jshint');
- grunt.loadNpmTasks('grunt-contrib-qunit');
- grunt.loadNpmTasks('grunt-contrib-concat');
- grunt.loadNpmTasks('grunt-jsdoc');
- grunt.loadNpmTasks('grunt-shell-spawn');
+ grunt.loadNpmTasks("grunt-contrib-uglify");
+ grunt.loadNpmTasks("grunt-contrib-jshint");
+ grunt.loadNpmTasks("grunt-contrib-qunit");
+ grunt.loadNpmTasks("grunt-contrib-concat");
+ grunt.loadNpmTasks("grunt-jsdoc");
+ grunt.loadNpmTasks("grunt-shell-spawn");
- grunt.registerTask('wait', 'Wait just one second for the server to start', function () {
- var done = this.async();
- setTimeout(function() {
- done(true);
- }, 1000);
- });
+ grunt.registerTask(
+ "wait",
+ "Wait just one second for the server to start",
+ function () {
+ var done = this.async();
+ setTimeout(function () {
+ done(true);
+ }, 1000);
+ },
+ );
- grunt.registerTask('CreateDirectories', 'Creating required local directories', function () {
- grunt.file.mkdir('test/build/js/lib');
- grunt.file.mkdir('test/gen-js');
- grunt.file.mkdir('test/gen-js-jquery');
- grunt.file.mkdir('test/gen-nodejs');
- grunt.file.mkdir('test/gen-js-es6');
- grunt.file.mkdir('test/gen-nodejs-es6');
-});
+ grunt.registerTask(
+ "CreateDirectories",
+ "Creating required local directories",
+ function () {
+ grunt.file.mkdir("test/build/js/lib");
+ grunt.file.mkdir("test/gen-js");
+ grunt.file.mkdir("test/gen-js-jquery");
+ grunt.file.mkdir("test/gen-nodejs");
+ grunt.file.mkdir("test/gen-js-es6");
+ grunt.file.mkdir("test/gen-nodejs-es6");
+ },
+ );
- grunt.registerTask('installAndGenerate', [
- 'CreateDirectories',
- 'shell:InstallThriftJS',
- 'shell:InstallThriftNodeJSDep',
- 'shell:ThriftGen',
- 'shell:ThriftGenDeepConstructor',
- 'shell:ThriftGenDoubleConstants',
- 'shell:InstallTestLibs',
- 'shell:ThriftBrowserifyNodeInt64',
- 'shell:ThriftGenInt64'
+ grunt.registerTask("installAndGenerate", [
+ "CreateDirectories",
+ "shell:InstallThriftJS",
+ "shell:InstallThriftNodeJSDep",
+ "shell:ThriftGen",
+ "shell:ThriftGenDeepConstructor",
+ "shell:ThriftGenDoubleConstants",
+ "shell:InstallTestLibs",
+ "shell:ThriftBrowserifyNodeInt64",
+ "shell:ThriftGenInt64",
]);
- grunt.registerTask('test', [
- 'installAndGenerate',
- 'jshint',
- 'shell:ThriftTestServer',
- 'shell:ThriftTestServer_TLS',
- 'shell:ThriftTestServerES6',
- 'shell:ThriftTestServerES6_TLS',
- 'wait',
- 'qunit:ThriftDeepConstructor',
- 'qunit:ThriftJS',
- 'qunit:ThriftJS_TLS',
- 'qunit:ThriftJS_DoubleRendering',
- 'qunit:ThriftWS',
- 'qunit:ThriftJSJQ',
- 'qunit:ThriftJSJQ_TLS',
- 'qunit:ThriftWSES6',
- 'qunit:ThriftJS_Int64',
- 'shell:ThriftTestServer:kill',
- 'shell:ThriftTestServer_TLS:kill',
- 'shell:ThriftTestServerES6:kill',
- 'shell:ThriftTestServerES6_TLS:kill',
+ grunt.registerTask("test", [
+ "installAndGenerate",
+ "jshint",
+ "shell:ThriftTestServer",
+ "shell:ThriftTestServer_TLS",
+ "shell:ThriftTestServerES6",
+ "shell:ThriftTestServerES6_TLS",
+ "wait",
+ "qunit:ThriftDeepConstructor",
+ "qunit:ThriftJS",
+ "qunit:ThriftJS_TLS",
+ "qunit:ThriftJS_DoubleRendering",
+ "qunit:ThriftWS",
+ "qunit:ThriftJSJQ",
+ "qunit:ThriftJSJQ_TLS",
+ "qunit:ThriftWSES6",
+ "qunit:ThriftJS_Int64",
+ "shell:ThriftTestServer:kill",
+ "shell:ThriftTestServer_TLS:kill",
+ "shell:ThriftTestServerES6:kill",
+ "shell:ThriftTestServerES6_TLS:kill",
]);
- grunt.registerTask('default', ['test', 'concat', 'uglify', 'jsdoc']);
+ grunt.registerTask("default", ["test", "concat", "uglify", "jsdoc"]);
};
diff --git a/lib/nodejs/examples/client.js b/lib/nodejs/examples/client.js
index c83b342..29dac26 100644
--- a/lib/nodejs/examples/client.js
+++ b/lib/nodejs/examples/client.js
@@ -16,28 +16,30 @@
* specific language governing permissions and limitations
* under the License.
*/
-var thrift = require('thrift');
+var thrift = require("thrift");
-var UserStorage = require('./gen-nodejs/UserStorage.js'),
- ttypes = require('./gen-nodejs/user_types');
+var UserStorage = require("./gen-nodejs/UserStorage.js"),
+ ttypes = require("./gen-nodejs/user_types");
-var connection = thrift.createConnection('localhost', 9090),
- client = thrift.createClient(UserStorage, connection);
+var connection = thrift.createConnection("localhost", 9090),
+ client = thrift.createClient(UserStorage, connection);
-var user = new ttypes.UserProfile({uid: 1,
- name: "Mark Slee",
- blurb: "I'll find something to put here."});
+var user = new ttypes.UserProfile({
+ uid: 1,
+ name: "Mark Slee",
+ blurb: "I'll find something to put here.",
+});
-connection.on('error', function(err) {
+connection.on("error", function (err) {
console.error(err);
});
-client.store(user, function(err, response) {
+client.store(user, function (err, response) {
if (err) {
console.error(err);
} else {
console.log("client stored:", user.uid);
- client.retrieve(user.uid, function(err, responseUser) {
+ client.retrieve(user.uid, function (err, responseUser) {
if (err) {
console.error(err);
} else {
diff --git a/lib/nodejs/examples/client_multitransport.js b/lib/nodejs/examples/client_multitransport.js
index 1e37de3..05e5c31 100644
--- a/lib/nodejs/examples/client_multitransport.js
+++ b/lib/nodejs/examples/client_multitransport.js
@@ -16,43 +16,61 @@
* specific language governing permissions and limitations
* under the License.
*/
-var thrift = require('thrift'),
- ttransport = require('thrift/transport');
+var thrift = require("thrift"),
+ ttransport = require("thrift/transport");
-var UserStorage = require('./gen-nodejs/UserStorage'),
- ttypes = require('./gen-nodejs/user_types');
+var UserStorage = require("./gen-nodejs/UserStorage"),
+ ttypes = require("./gen-nodejs/user_types");
-var f_conn = thrift.createConnection('localhost', 9090), // default: framed
- f_client = thrift.createClient(UserStorage, f_conn);
-var b_conn = thrift.createConnection('localhost', 9091, {transport: ttransport.TBufferedTransport}),
- b_client = thrift.createClient(UserStorage, b_conn);
-var user1 = new ttypes.UserProfile({uid: 1,
- name: "Mark Slee",
- blurb: "I'll find something to put here."});
-var user2 = new ttypes.UserProfile({uid: 2,
- name: "Satoshi Tagomori",
- blurb: "ok, let's test with buffered transport."});
+var f_conn = thrift.createConnection("localhost", 9090), // default: framed
+ f_client = thrift.createClient(UserStorage, f_conn);
+var b_conn = thrift.createConnection("localhost", 9091, {
+ transport: ttransport.TBufferedTransport,
+ }),
+ b_client = thrift.createClient(UserStorage, b_conn);
+var user1 = new ttypes.UserProfile({
+ uid: 1,
+ name: "Mark Slee",
+ blurb: "I'll find something to put here.",
+});
+var user2 = new ttypes.UserProfile({
+ uid: 2,
+ name: "Satoshi Tagomori",
+ blurb: "ok, let's test with buffered transport.",
+});
-f_conn.on('error', function(err) {
+f_conn.on("error", function (err) {
console.error("framed:", err);
});
-f_client.store(user1, function(err, response) {
- if (err) { console.error(err); return; }
+f_client.store(user1, function (err, response) {
+ if (err) {
+ console.error(err);
+ return;
+ }
console.log("stored:", user1.uid, " as ", user1.name);
- b_client.retrieve(user1.uid, function(err, responseUser) {
- if (err) { console.error(err); return; }
+ b_client.retrieve(user1.uid, function (err, responseUser) {
+ if (err) {
+ console.error(err);
+ return;
+ }
console.log("retrieved:", responseUser.uid, " as ", responseUser.name);
});
});
-b_client.store(user2, function(err, response) {
- if (err) { console.error(err); return; }
+b_client.store(user2, function (err, response) {
+ if (err) {
+ console.error(err);
+ return;
+ }
console.log("stored:", user2.uid, " as ", user2.name);
- f_client.retrieve(user2.uid, function(err, responseUser) {
- if (err) { console.error(err); return; }
+ f_client.retrieve(user2.uid, function (err, responseUser) {
+ if (err) {
+ console.error(err);
+ return;
+ }
console.log("retrieved:", responseUser.uid, " as ", responseUser.name);
});
});
diff --git a/lib/nodejs/examples/hello.js b/lib/nodejs/examples/hello.js
index 8b7c4e4..5f1b682 100644
--- a/lib/nodejs/examples/hello.js
+++ b/lib/nodejs/examples/hello.js
@@ -16,46 +16,46 @@
* specific language governing permissions and limitations
* under the License.
*/
-var thrift = require('thrift');
-var HelloSvc = require('./gen-nodejs/HelloSvc.js');
-var TimesTwoSvc = require('./gen-nodejs/TimesTwo.js');
+var thrift = require("thrift");
+var HelloSvc = require("./gen-nodejs/HelloSvc.js");
+var TimesTwoSvc = require("./gen-nodejs/TimesTwo.js");
var helloHandler = {
- hello_func: function(result) {
- this.call_counter = this.call_counter || 0;
- console.log("Client call: " + (++this.call_counter));
- result(null, "Hello Apache Thrift for JavaScript " + this.call_counter);
- }
-}
+ hello_func: function (result) {
+ this.call_counter = this.call_counter || 0;
+ console.log("Client call: " + ++this.call_counter);
+ result(null, "Hello Apache Thrift for JavaScript " + this.call_counter);
+ },
+};
var timesTwoHandler = {
- dbl: function(val, result) {
- console.log("Client call: " + val);
- result(null, val * 2);
- }
-}
+ dbl: function (val, result) {
+ console.log("Client call: " + val);
+ result(null, val * 2);
+ },
+};
var helloService = {
- transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol,
- processor: HelloSvc,
- handler: helloHandler
+ transport: thrift.TBufferedTransport,
+ protocol: thrift.TJSONProtocol,
+ processor: HelloSvc,
+ handler: helloHandler,
};
var dblService = {
- transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol,
- processor: TimesTwoSvc,
- handler: timesTwoHandler
+ transport: thrift.TBufferedTransport,
+ protocol: thrift.TJSONProtocol,
+ processor: TimesTwoSvc,
+ handler: timesTwoHandler,
};
var ServerOptions = {
- files: ".",
- services: {
- "/hello": helloService,
- "/dbl": dblService,
- }
-}
+ files: ".",
+ services: {
+ "/hello": helloService,
+ "/dbl": dblService,
+ },
+};
var server = thrift.createWebServer(ServerOptions);
var port = 8585;
diff --git a/lib/nodejs/examples/httpClient.js b/lib/nodejs/examples/httpClient.js
index 19cc0c3..155b5f4 100644
--- a/lib/nodejs/examples/httpClient.js
+++ b/lib/nodejs/examples/httpClient.js
@@ -1,23 +1,21 @@
-var thrift = require('thrift');
-var helloSvc = require('./gen-nodejs/HelloSvc.js');
+var thrift = require("thrift");
+var helloSvc = require("./gen-nodejs/HelloSvc.js");
var options = {
- transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol,
- path: "/hello",
- headers: {"Connection": "close"},
- https: false
+ transport: thrift.TBufferedTransport,
+ protocol: thrift.TJSONProtocol,
+ path: "/hello",
+ headers: { Connection: "close" },
+ https: false,
};
var connection = thrift.createHttpConnection("localhost", 9090, options);
var client = thrift.createHttpClient(helloSvc, connection);
-connection.on("error", function(err) {
- console.log("Error: " + err);
+connection.on("error", function (err) {
+ console.log("Error: " + err);
});
-client.hello_func(function(error, result) {
- console.log("Msg from server: " + result);
+client.hello_func(function (error, result) {
+ console.log("Msg from server: " + result);
});
-
-
diff --git a/lib/nodejs/examples/httpServer.js b/lib/nodejs/examples/httpServer.js
index acae136..c4cbc9f 100644
--- a/lib/nodejs/examples/httpServer.js
+++ b/lib/nodejs/examples/httpServer.js
@@ -1,31 +1,30 @@
-var thrift = require('thrift');
-var helloSvc = require('./gen-nodejs/HelloSvc');
+var thrift = require("thrift");
+var helloSvc = require("./gen-nodejs/HelloSvc");
-//ServiceHandler: Implement the hello service
+//ServiceHandler: Implement the hello service
var helloHandler = {
hello_func: function (result) {
console.log("Received Hello call");
result(null, "Hello from Node.js");
- }
+ },
};
//ServiceOptions: The I/O stack for the service
-var helloSvcOpt = {
- handler: helloHandler,
- processor: helloSvc,
- protocol: thrift.TJSONProtocol,
- transport: thrift.TBufferedTransport
-};
+var helloSvcOpt = {
+ handler: helloHandler,
+ processor: helloSvc,
+ protocol: thrift.TJSONProtocol,
+ transport: thrift.TBufferedTransport,
+};
//ServerOptions: Define server features
-var serverOpt = {
- services: {
- "/hello": helloSvcOpt
- }
-}
+var serverOpt = {
+ services: {
+ "/hello": helloSvcOpt,
+ },
+};
-//Create and start the web server
-var port = 9090;
-thrift.createWebServer(serverOpt).listen(port);
+//Create and start the web server
+var port = 9090;
+thrift.createWebServer(serverOpt).listen(port);
console.log("Http/Thrift Server running on port: " + port);
-
diff --git a/lib/nodejs/examples/parse.js b/lib/nodejs/examples/parse.js
index 168a1ae..8513e4c 100644
--- a/lib/nodejs/examples/parse.js
+++ b/lib/nodejs/examples/parse.js
@@ -35,11 +35,11 @@
*/
function parseThrift(thriftEncodedData, callback) {
- var thrift = require('thrift');
+ var thrift = require("thrift");
var transport = new thrift.TFramedTransport(thriftEncodedData);
- var protocol = new thrift.TBinaryProtocol(transport);
+ var protocol = new thrift.TBinaryProtocol(transport);
- var clientClass = require('../gen-nodejs/GENERATED').YOUR_CLASS_NAME;
+ var clientClass = require("../gen-nodejs/GENERATED").YOUR_CLASS_NAME;
var client = new clientClass();
client.read(protocol);
callback(null, client);
diff --git a/lib/nodejs/examples/server.js b/lib/nodejs/examples/server.js
index 1c482fe..41492cb 100644
--- a/lib/nodejs/examples/server.js
+++ b/lib/nodejs/examples/server.js
@@ -16,21 +16,21 @@
* specific language governing permissions and limitations
* under the License.
*/
-var thrift = require('thrift');
+var thrift = require("thrift");
-var UserStorage = require('./gen-nodejs/UserStorage.js'),
- ttypes = require('./gen-nodejs/user_types');
+var UserStorage = require("./gen-nodejs/UserStorage.js"),
+ ttypes = require("./gen-nodejs/user_types");
var users = {};
var server = thrift.createServer(UserStorage, {
- store: function(user, result) {
+ store: function (user, result) {
console.log("server stored:", user.uid);
users[user.uid] = user;
result(null);
},
- retrieve: function(uid, result) {
+ retrieve: function (uid, result) {
console.log("server retrieved:", uid);
result(null, users[uid]);
},
diff --git a/lib/nodejs/examples/server_http.js b/lib/nodejs/examples/server_http.js
index ef2dc83..235f675 100644
--- a/lib/nodejs/examples/server_http.js
+++ b/lib/nodejs/examples/server_http.js
@@ -16,38 +16,46 @@
* specific language governing permissions and limitations
* under the License.
*/
-var connect = require('connect');
-var thrift = require('thrift');
+var connect = require("connect");
+var thrift = require("thrift");
-var UserStorage = require('./gen-nodejs/UserStorage'),
- ttypes = require('./gen-nodejs/user_types');
+var UserStorage = require("./gen-nodejs/UserStorage"),
+ ttypes = require("./gen-nodejs/user_types");
var users = {};
-var store = function(user, result) {
+var store = function (user, result) {
console.log("stored:", user.uid);
users[user.uid] = user;
result(null);
};
-var retrieve = function(uid, result) {
+var retrieve = function (uid, result) {
console.log("retrieved:", uid);
result(null, users[uid]);
};
var server_http = thrift.createHttpServer(UserStorage, {
store: store,
- retrieve: retrieve
+ retrieve: retrieve,
});
server_http.listen(9090);
-var server_connect = connect(thrift.httpMiddleware(UserStorage, {
- store: store,
- retrieve: retrieve
-}));
+var server_connect = connect(
+ thrift.httpMiddleware(UserStorage, {
+ store: store,
+ retrieve: retrieve,
+ }),
+);
server_http.listen(9091);
-var server_connect_json = connect(thrift.httpMiddleware(UserStorage, {
- store: store,
- retrieve: retrieve
-}, {protocol: thrift.TJSONProtocol}));
+var server_connect_json = connect(
+ thrift.httpMiddleware(
+ UserStorage,
+ {
+ store: store,
+ retrieve: retrieve,
+ },
+ { protocol: thrift.TJSONProtocol },
+ ),
+);
server_connect_json.listen(9092);
diff --git a/lib/nodejs/examples/server_multitransport.js b/lib/nodejs/examples/server_multitransport.js
index a348e68..3dc0b17 100644
--- a/lib/nodejs/examples/server_multitransport.js
+++ b/lib/nodejs/examples/server_multitransport.js
@@ -16,31 +16,35 @@
* specific language governing permissions and limitations
* under the License.
*/
-var thrift = require('thrift'),
- ttransport = require('thrift/transport');
+var thrift = require("thrift"),
+ ttransport = require("thrift/transport");
-var UserStorage = require('./gen-nodejs/UserStorage'),
- ttypes = require('./gen-nodejs/user_types');
+var UserStorage = require("./gen-nodejs/UserStorage"),
+ ttypes = require("./gen-nodejs/user_types");
var users = {};
-var store = function(user, result) {
+var store = function (user, result) {
console.log("stored:", user.uid);
users[user.uid] = user;
result(null);
};
-var retrieve = function(uid, result) {
+var retrieve = function (uid, result) {
console.log("retrieved:", uid);
result(null, users[uid]);
};
var server_framed = thrift.createServer(UserStorage, {
store: store,
- retrieve: retrieve
+ retrieve: retrieve,
});
server_framed.listen(9090);
-var server_buffered = thrift.createServer(UserStorage, {
- store: store,
- retrieve: retrieve
-}, {transport: ttransport.TBufferedTransport});
+var server_buffered = thrift.createServer(
+ UserStorage,
+ {
+ store: store,
+ retrieve: retrieve,
+ },
+ { transport: ttransport.TBufferedTransport },
+);
server_buffered.listen(9091);
diff --git a/lib/nodejs/lib/thrift/binary.js b/lib/nodejs/lib/thrift/binary.js
index 9813ffd..e8bbee7 100644
--- a/lib/nodejs/lib/thrift/binary.js
+++ b/lib/nodejs/lib/thrift/binary.js
@@ -26,11 +26,11 @@
var POW_52 = Math.pow(2, 52);
var POW_1022 = Math.pow(2, 1022);
-exports.readByte = function(b){
- return b > 127 ? b-256 : b;
+exports.readByte = function (b) {
+ return b > 127 ? b - 256 : b;
};
-exports.readI16 = function(buff, off) {
+exports.readI16 = function (buff, off) {
off = off || 0;
var v = buff[off + 1];
v += buff[off] << 8;
@@ -40,7 +40,7 @@
return v;
};
-exports.readI32 = function(buff, off) {
+exports.readI32 = function (buff, off) {
off = off || 0;
var v = buff[off + 3];
v += buff[off + 2] << 8;
@@ -52,14 +52,14 @@
return v;
};
-exports.writeI16 = function(buff, v) {
+exports.writeI16 = function (buff, v) {
buff[1] = v & 0xff;
v >>= 8;
buff[0] = v & 0xff;
return buff;
};
-exports.writeI32 = function(buff, v) {
+exports.writeI32 = function (buff, v) {
buff[3] = v & 0xff;
v >>= 8;
buff[2] = v & 0xff;
@@ -70,26 +70,26 @@
return buff;
};
-exports.readDouble = function(buff, off) {
+exports.readDouble = function (buff, off) {
off = off || 0;
var signed = buff[off] & 0x80;
- var e = (buff[off+1] & 0xF0) >> 4;
- e += (buff[off] & 0x7F) << 4;
+ var e = (buff[off + 1] & 0xf0) >> 4;
+ e += (buff[off] & 0x7f) << 4;
- var m = buff[off+7];
- m += buff[off+6] << 8;
- m += buff[off+5] << 16;
- m += buff[off+4] * POW_24;
- m += buff[off+3] * POW_32;
- m += buff[off+2] * POW_40;
- m += (buff[off+1] & 0x0F) * POW_48;
+ var m = buff[off + 7];
+ m += buff[off + 6] << 8;
+ m += buff[off + 5] << 16;
+ m += buff[off + 4] * POW_24;
+ m += buff[off + 3] * POW_32;
+ m += buff[off + 2] * POW_40;
+ m += (buff[off + 1] & 0x0f) * POW_48;
switch (e) {
case 0:
e = -1022;
break;
case 2047:
- return m ? NaN : (signed ? -Infinity : Infinity);
+ return m ? NaN : signed ? -Infinity : Infinity;
default:
m += POW_52;
e -= 1023;
@@ -106,10 +106,10 @@
* Based on code from the jspack module:
* http://code.google.com/p/jspack/
*/
-exports.writeDouble = function(buff, v) {
+exports.writeDouble = function (buff, v) {
var m, e, c;
- buff[0] = (v < 0 ? 0x80 : 0x00);
+ buff[0] = v < 0 ? 0x80 : 0x00;
v = Math.abs(v);
if (v !== v) {
@@ -127,22 +127,17 @@
c *= 2;
}
- if (e + 1023 >= 2047)
- {
+ if (e + 1023 >= 2047) {
// Overflow
m = 0;
e = 2047;
- }
- else if (e + 1023 >= 1)
- {
+ } else if (e + 1023 >= 1) {
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
- m = (v*c-1) * POW_52;
+ m = (v * c - 1) * POW_52;
e += 1023;
- }
- else
- {
+ } else {
// Denormalized - also catches the '0' case, somewhat by chance
- m = (v * POW_1022) * POW_52;
+ m = v * POW_1022 * POW_52;
e = 0;
}
}
diff --git a/lib/nodejs/lib/thrift/binary_protocol.js b/lib/nodejs/lib/thrift/binary_protocol.js
index af8836c..fc4df4a 100644
--- a/lib/nodejs/lib/thrift/binary_protocol.js
+++ b/lib/nodejs/lib/thrift/binary_protocol.js
@@ -17,10 +17,10 @@
* under the License.
*/
-var log = require('./log');
-var binary = require('./binary');
-var Int64 = require('node-int64');
-var Thrift = require('./thrift');
+var log = require("./log");
+var binary = require("./binary");
+var Int64 = require("node-int64");
+var Thrift = require("./thrift");
var Type = Thrift.Type;
module.exports = TBinaryProtocol;
@@ -29,96 +29,90 @@
// The largest integer value which can be represented in JavaScript is +/-2^53.
// Bitwise operations convert numbers to 32 bit integers but perform sign extension
// upon assigning values back to variables.
-var VERSION_MASK = -65536, // 0xffff0000
- VERSION_1 = -2147418112, // 0x80010000
- TYPE_MASK = 0x000000ff;
+var VERSION_MASK = -65536, // 0xffff0000
+ VERSION_1 = -2147418112, // 0x80010000
+ TYPE_MASK = 0x000000ff;
TBinaryProtocol.VERSION_MASK = VERSION_MASK;
TBinaryProtocol.VERSION_1 = VERSION_1;
-TBinaryProtocol.TYPE_MASK = TYPE_MASK
+TBinaryProtocol.TYPE_MASK = TYPE_MASK;
function TBinaryProtocol(trans, strictRead, strictWrite) {
this.trans = trans;
- this.strictRead = (strictRead !== undefined ? strictRead : false);
- this.strictWrite = (strictWrite !== undefined ? strictWrite : true);
+ this.strictRead = strictRead !== undefined ? strictRead : false;
+ this.strictWrite = strictWrite !== undefined ? strictWrite : true;
this._seqid = null;
-};
+}
-TBinaryProtocol.prototype.flush = function() {
+TBinaryProtocol.prototype.flush = function () {
return this.trans.flush();
};
-TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
- if (this.strictWrite) {
- this.writeI32(VERSION_1 | type);
- this.writeString(name);
- this.writeI32(seqid);
- } else {
- this.writeString(name);
- this.writeByte(type);
- this.writeI32(seqid);
- }
- // Record client seqid to find callback again
- if (this._seqid !== null) {
- log.warning('SeqId already set', { 'name': name });
- } else {
- this._seqid = seqid;
- this.trans.setCurrSeqId(seqid);
- }
+TBinaryProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
+ if (this.strictWrite) {
+ this.writeI32(VERSION_1 | type);
+ this.writeString(name);
+ this.writeI32(seqid);
+ } else {
+ this.writeString(name);
+ this.writeByte(type);
+ this.writeI32(seqid);
+ }
+ // Record client seqid to find callback again
+ if (this._seqid !== null) {
+ log.warning("SeqId already set", { name: name });
+ } else {
+ this._seqid = seqid;
+ this.trans.setCurrSeqId(seqid);
+ }
};
-TBinaryProtocol.prototype.writeMessageEnd = function() {
- if (this._seqid !== null) {
- this._seqid = null;
- } else {
- log.warning('No seqid to unset');
- }
+TBinaryProtocol.prototype.writeMessageEnd = function () {
+ if (this._seqid !== null) {
+ this._seqid = null;
+ } else {
+ log.warning("No seqid to unset");
+ }
};
-TBinaryProtocol.prototype.writeStructBegin = function(name) {
-};
+TBinaryProtocol.prototype.writeStructBegin = function (name) {};
-TBinaryProtocol.prototype.writeStructEnd = function() {
-};
+TBinaryProtocol.prototype.writeStructEnd = function () {};
-TBinaryProtocol.prototype.writeFieldBegin = function(name, type, id) {
+TBinaryProtocol.prototype.writeFieldBegin = function (name, type, id) {
this.writeByte(type);
this.writeI16(id);
};
-TBinaryProtocol.prototype.writeFieldEnd = function() {
-};
+TBinaryProtocol.prototype.writeFieldEnd = function () {};
-TBinaryProtocol.prototype.writeFieldStop = function() {
+TBinaryProtocol.prototype.writeFieldStop = function () {
this.writeByte(Type.STOP);
};
-TBinaryProtocol.prototype.writeMapBegin = function(ktype, vtype, size) {
+TBinaryProtocol.prototype.writeMapBegin = function (ktype, vtype, size) {
this.writeByte(ktype);
this.writeByte(vtype);
this.writeI32(size);
};
-TBinaryProtocol.prototype.writeMapEnd = function() {
-};
+TBinaryProtocol.prototype.writeMapEnd = function () {};
-TBinaryProtocol.prototype.writeListBegin = function(etype, size) {
+TBinaryProtocol.prototype.writeListBegin = function (etype, size) {
this.writeByte(etype);
this.writeI32(size);
};
-TBinaryProtocol.prototype.writeListEnd = function() {
-};
+TBinaryProtocol.prototype.writeListEnd = function () {};
-TBinaryProtocol.prototype.writeSetBegin = function(etype, size) {
+TBinaryProtocol.prototype.writeSetBegin = function (etype, size) {
this.writeByte(etype);
this.writeI32(size);
};
-TBinaryProtocol.prototype.writeSetEnd = function() {
-};
+TBinaryProtocol.prototype.writeSetEnd = function () {};
-TBinaryProtocol.prototype.writeBool = function(bool) {
+TBinaryProtocol.prototype.writeBool = function (bool) {
if (bool) {
this.writeByte(1);
} else {
@@ -126,19 +120,19 @@
}
};
-TBinaryProtocol.prototype.writeByte = function(b) {
+TBinaryProtocol.prototype.writeByte = function (b) {
this.trans.write(new Buffer([b]));
};
-TBinaryProtocol.prototype.writeI16 = function(i16) {
+TBinaryProtocol.prototype.writeI16 = function (i16) {
this.trans.write(binary.writeI16(new Buffer(2), i16));
};
-TBinaryProtocol.prototype.writeI32 = function(i32) {
+TBinaryProtocol.prototype.writeI32 = function (i32) {
this.trans.write(binary.writeI32(new Buffer(4), i32));
};
-TBinaryProtocol.prototype.writeI64 = function(i64) {
+TBinaryProtocol.prototype.writeI64 = function (i64) {
if (i64.buffer) {
this.trans.write(i64.buffer);
} else {
@@ -146,108 +140,110 @@
}
};
-TBinaryProtocol.prototype.writeDouble = function(dub) {
+TBinaryProtocol.prototype.writeDouble = function (dub) {
this.trans.write(binary.writeDouble(new Buffer(8), dub));
};
-TBinaryProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) {
- if (typeof(arg) === 'string') {
+TBinaryProtocol.prototype.writeStringOrBinary = function (name, encoding, arg) {
+ if (typeof arg === "string") {
this.writeI32(Buffer.byteLength(arg, encoding));
this.trans.write(new Buffer(arg, encoding));
- } else if ((arg instanceof Buffer) ||
- (Object.prototype.toString.call(arg) == '[object Uint8Array]')) {
+ } else if (
+ arg instanceof Buffer ||
+ Object.prototype.toString.call(arg) == "[object Uint8Array]"
+ ) {
// Buffers in Node.js under Browserify may extend UInt8Array instead of
// defining a new object. We detect them here so we can write them
// correctly
this.writeI32(arg.length);
this.trans.write(arg);
} else {
- throw new Error(name + ' called without a string/Buffer argument: ' + arg);
+ throw new Error(name + " called without a string/Buffer argument: " + arg);
}
};
-TBinaryProtocol.prototype.writeString = function(arg) {
- this.writeStringOrBinary('writeString', 'utf8', arg);
+TBinaryProtocol.prototype.writeString = function (arg) {
+ this.writeStringOrBinary("writeString", "utf8", arg);
};
-TBinaryProtocol.prototype.writeBinary = function(arg) {
- this.writeStringOrBinary('writeBinary', 'binary', arg);
+TBinaryProtocol.prototype.writeBinary = function (arg) {
+ this.writeStringOrBinary("writeBinary", "binary", arg);
};
-TBinaryProtocol.prototype.readMessageBegin = function() {
+TBinaryProtocol.prototype.readMessageBegin = function () {
var sz = this.readI32();
var type, name, seqid;
if (sz < 0) {
var version = sz & VERSION_MASK;
if (version != VERSION_1) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad version in readMessageBegin: " + sz);
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.BAD_VERSION,
+ "Bad version in readMessageBegin: " + sz,
+ );
}
type = sz & TYPE_MASK;
name = this.readString();
seqid = this.readI32();
} else {
if (this.strictRead) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "No protocol version header");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.BAD_VERSION,
+ "No protocol version header",
+ );
}
name = this.trans.read(sz);
type = this.readByte();
seqid = this.readI32();
}
- return {fname: name, mtype: type, rseqid: seqid};
+ return { fname: name, mtype: type, rseqid: seqid };
};
-TBinaryProtocol.prototype.readMessageEnd = function() {
+TBinaryProtocol.prototype.readMessageEnd = function () {};
+
+TBinaryProtocol.prototype.readStructBegin = function () {
+ return { fname: "" };
};
-TBinaryProtocol.prototype.readStructBegin = function() {
- return {fname: ''};
-};
+TBinaryProtocol.prototype.readStructEnd = function () {};
-TBinaryProtocol.prototype.readStructEnd = function() {
-};
-
-TBinaryProtocol.prototype.readFieldBegin = function() {
+TBinaryProtocol.prototype.readFieldBegin = function () {
var type = this.readByte();
if (type == Type.STOP) {
- return {fname: null, ftype: type, fid: 0};
+ return { fname: null, ftype: type, fid: 0 };
}
var id = this.readI16();
- return {fname: null, ftype: type, fid: id};
+ return { fname: null, ftype: type, fid: id };
};
-TBinaryProtocol.prototype.readFieldEnd = function() {
-};
+TBinaryProtocol.prototype.readFieldEnd = function () {};
-TBinaryProtocol.prototype.readMapBegin = function() {
+TBinaryProtocol.prototype.readMapBegin = function () {
var ktype = this.readByte();
var vtype = this.readByte();
var size = this.readI32();
- return {ktype: ktype, vtype: vtype, size: size};
+ return { ktype: ktype, vtype: vtype, size: size };
};
-TBinaryProtocol.prototype.readMapEnd = function() {
-};
+TBinaryProtocol.prototype.readMapEnd = function () {};
-TBinaryProtocol.prototype.readListBegin = function() {
+TBinaryProtocol.prototype.readListBegin = function () {
var etype = this.readByte();
var size = this.readI32();
- return {etype: etype, size: size};
+ return { etype: etype, size: size };
};
-TBinaryProtocol.prototype.readListEnd = function() {
-};
+TBinaryProtocol.prototype.readListEnd = function () {};
-TBinaryProtocol.prototype.readSetBegin = function() {
+TBinaryProtocol.prototype.readSetBegin = function () {
var etype = this.readByte();
var size = this.readI32();
- return {etype: etype, size: size};
+ return { etype: etype, size: size };
};
-TBinaryProtocol.prototype.readSetEnd = function() {
-};
+TBinaryProtocol.prototype.readSetEnd = function () {};
-TBinaryProtocol.prototype.readBool = function() {
+TBinaryProtocol.prototype.readBool = function () {
var b = this.readByte();
if (b === 0) {
return false;
@@ -255,56 +251,62 @@
return true;
};
-TBinaryProtocol.prototype.readByte = function() {
+TBinaryProtocol.prototype.readByte = function () {
return this.trans.readByte();
};
-TBinaryProtocol.prototype.readI16 = function() {
+TBinaryProtocol.prototype.readI16 = function () {
return this.trans.readI16();
};
-TBinaryProtocol.prototype.readI32 = function() {
+TBinaryProtocol.prototype.readI32 = function () {
return this.trans.readI32();
};
-TBinaryProtocol.prototype.readI64 = function() {
+TBinaryProtocol.prototype.readI64 = function () {
var buff = this.trans.read(8);
return new Int64(buff);
};
-TBinaryProtocol.prototype.readDouble = function() {
+TBinaryProtocol.prototype.readDouble = function () {
return this.trans.readDouble();
};
-TBinaryProtocol.prototype.readBinary = function() {
+TBinaryProtocol.prototype.readBinary = function () {
var len = this.readI32();
if (len === 0) {
return new Buffer(0);
}
if (len < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative binary size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative binary size",
+ );
}
return this.trans.read(len);
};
-TBinaryProtocol.prototype.readString = function() {
+TBinaryProtocol.prototype.readString = function () {
var len = this.readI32();
if (len === 0) {
return "";
}
if (len < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative string size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative string size",
+ );
}
return this.trans.readString(len);
};
-TBinaryProtocol.prototype.getTransport = function() {
+TBinaryProtocol.prototype.getTransport = function () {
return this.trans;
};
-TBinaryProtocol.prototype.skip = function(type) {
+TBinaryProtocol.prototype.skip = function (type) {
switch (type) {
case Type.BOOL:
this.readBool();
@@ -362,6 +364,6 @@
this.readListEnd();
break;
default:
- throw new Error("Invalid type: " + type);
+ throw new Error("Invalid type: " + type);
}
};
diff --git a/lib/nodejs/lib/thrift/browser.js b/lib/nodejs/lib/thrift/browser.js
index 5915cf6..5c843d0 100644
--- a/lib/nodejs/lib/thrift/browser.js
+++ b/lib/nodejs/lib/thrift/browser.js
@@ -16,42 +16,42 @@
* specific language governing permissions and limitations
* under the License.
*/
-exports.Thrift = require('./thrift');
+exports.Thrift = require("./thrift");
-var wsConnection = require('./ws_connection');
+var wsConnection = require("./ws_connection");
exports.WSConnection = wsConnection.WSConnection;
exports.createWSConnection = wsConnection.createWSConnection;
exports.createWSClient = wsConnection.createWSClient;
-var xhrConnection = require('./xhr_connection');
+var xhrConnection = require("./xhr_connection");
exports.XHRConnection = xhrConnection.XHRConnection;
exports.createXHRConnection = xhrConnection.createXHRConnection;
exports.createXHRClient = xhrConnection.createXHRClient;
-var ohosConnection = require('./ohos_connection');
+var ohosConnection = require("./ohos_connection");
exports.OhosConnection = ohosConnection.OhosConnection;
exports.createOhosConnection = ohosConnection.createOhosConnection;
exports.createOhosClient = ohosConnection.createOhosClient;
-exports.createClient = require('./create_client');
+exports.createClient = require("./create_client");
-exports.Int64 = require('node-int64');
-exports.Q = require('q');
+exports.Int64 = require("node-int64");
+exports.Q = require("q");
-var mpxProtocol = require('./multiplexed_protocol');
+var mpxProtocol = require("./multiplexed_protocol");
exports.Multiplexer = mpxProtocol.Multiplexer;
/*
* Export transport and protocol so they can be used outside of a
* cassandra/server context
*/
-exports.TBufferedTransport = require('./buffered_transport');
-exports.TFramedTransport = require('./framed_transport');
-exports.TWebSocketTransport = require('./ws_transport');
+exports.TBufferedTransport = require("./buffered_transport");
+exports.TFramedTransport = require("./framed_transport");
+exports.TWebSocketTransport = require("./ws_transport");
-exports.Protocol = require('./json_protocol');
-exports.TJSONProtocol = require('./json_protocol');
-exports.TBinaryProtocol = require('./binary_protocol');
-exports.TCompactProtocol = require('./compact_protocol');
+exports.Protocol = require("./json_protocol");
+exports.TJSONProtocol = require("./json_protocol");
+exports.TBinaryProtocol = require("./binary_protocol");
+exports.TCompactProtocol = require("./compact_protocol");
-exports.InputBufferUnderrunError = require('./input_buffer_underrun_error');
+exports.InputBufferUnderrunError = require("./input_buffer_underrun_error");
diff --git a/lib/nodejs/lib/thrift/buffered_transport.js b/lib/nodejs/lib/thrift/buffered_transport.js
index f0d5d4a..27d682d 100644
--- a/lib/nodejs/lib/thrift/buffered_transport.js
+++ b/lib/nodejs/lib/thrift/buffered_transport.js
@@ -17,9 +17,9 @@
* under the License.
*/
-var binary = require('./binary');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
-var THeaderTransport = require('./header_transport');
+var binary = require("./binary");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
+var THeaderTransport = require("./header_transport");
module.exports = TBufferedTransport;
@@ -33,22 +33,22 @@
this.outBuffers = [];
this.outCount = 0;
this.onFlush = callback;
-};
+}
Object.setPrototypeOf(TBufferedTransport.prototype, THeaderTransport.prototype);
-TBufferedTransport.prototype.reset = function() {
+TBufferedTransport.prototype.reset = function () {
this.inBuf = new Buffer(this.defaultReadBufferSize);
this.readCursor = 0;
this.writeCursor = 0;
this.outBuffers = [];
this.outCount = 0;
-}
+};
-TBufferedTransport.receiver = function(callback, seqid) {
+TBufferedTransport.receiver = function (callback, seqid) {
var reader = new TBufferedTransport();
- return function(data) {
+ return function (data) {
if (reader.writeCursor + data.length > reader.inBuf.length) {
var buf = new Buffer(reader.writeCursor + data.length);
reader.inBuf.copy(buf, 0, 0, reader.writeCursor);
@@ -61,11 +61,12 @@
};
};
-
-TBufferedTransport.prototype.commitPosition = function(){
+TBufferedTransport.prototype.commitPosition = function () {
var unreadSize = this.writeCursor - this.readCursor;
- var bufSize = (unreadSize * 2 > this.defaultReadBufferSize) ?
- unreadSize * 2 : this.defaultReadBufferSize;
+ var bufSize =
+ unreadSize * 2 > this.defaultReadBufferSize
+ ? unreadSize * 2
+ : this.defaultReadBufferSize;
var buf = new Buffer(bufSize);
if (unreadSize > 0) {
this.inBuf.copy(buf, 0, this.readCursor, this.writeCursor);
@@ -75,34 +76,32 @@
this.inBuf = buf;
};
-TBufferedTransport.prototype.rollbackPosition = function(){
+TBufferedTransport.prototype.rollbackPosition = function () {
this.readCursor = 0;
-}
+};
- // TODO: Implement open/close support
-TBufferedTransport.prototype.isOpen = function() {
+// TODO: Implement open/close support
+TBufferedTransport.prototype.isOpen = function () {
return true;
};
-TBufferedTransport.prototype.open = function() {
-};
+TBufferedTransport.prototype.open = function () {};
-TBufferedTransport.prototype.close = function() {
-};
+TBufferedTransport.prototype.close = function () {};
- // Set the seqid of the message in the client
- // So that callbacks can be found
-TBufferedTransport.prototype.setCurrSeqId = function(seqid) {
+// Set the seqid of the message in the client
+// So that callbacks can be found
+TBufferedTransport.prototype.setCurrSeqId = function (seqid) {
this._seqid = seqid;
};
-TBufferedTransport.prototype.ensureAvailable = function(len) {
+TBufferedTransport.prototype.ensureAvailable = function (len) {
if (this.readCursor + len > this.writeCursor) {
throw new InputBufferUnderrunError();
}
};
-TBufferedTransport.prototype.read = function(len) {
+TBufferedTransport.prototype.read = function (len) {
this.ensureAvailable(len);
var buf = new Buffer(len);
this.inBuf.copy(buf, 0, this.readCursor, this.readCursor + len);
@@ -110,57 +109,61 @@
return buf;
};
-TBufferedTransport.prototype.readByte = function() {
+TBufferedTransport.prototype.readByte = function () {
this.ensureAvailable(1);
return binary.readByte(this.inBuf[this.readCursor++]);
};
-TBufferedTransport.prototype.readI16 = function() {
+TBufferedTransport.prototype.readI16 = function () {
this.ensureAvailable(2);
var i16 = binary.readI16(this.inBuf, this.readCursor);
this.readCursor += 2;
return i16;
};
-TBufferedTransport.prototype.readI32 = function() {
+TBufferedTransport.prototype.readI32 = function () {
this.ensureAvailable(4);
var i32 = binary.readI32(this.inBuf, this.readCursor);
this.readCursor += 4;
return i32;
};
-TBufferedTransport.prototype.readDouble = function() {
+TBufferedTransport.prototype.readDouble = function () {
this.ensureAvailable(8);
var d = binary.readDouble(this.inBuf, this.readCursor);
this.readCursor += 8;
return d;
};
-TBufferedTransport.prototype.readString = function(len) {
+TBufferedTransport.prototype.readString = function (len) {
this.ensureAvailable(len);
- var str = this.inBuf.toString('utf8', this.readCursor, this.readCursor + len);
+ var str = this.inBuf.toString("utf8", this.readCursor, this.readCursor + len);
this.readCursor += len;
return str;
};
-TBufferedTransport.prototype.borrow = function() {
- var obj = {buf: this.inBuf, readIndex: this.readCursor, writeIndex: this.writeCursor};
+TBufferedTransport.prototype.borrow = function () {
+ var obj = {
+ buf: this.inBuf,
+ readIndex: this.readCursor,
+ writeIndex: this.writeCursor,
+ };
return obj;
};
-TBufferedTransport.prototype.consume = function(bytesConsumed) {
+TBufferedTransport.prototype.consume = function (bytesConsumed) {
this.readCursor += bytesConsumed;
};
-TBufferedTransport.prototype.write = function(buf) {
- if (typeof(buf) === "string") {
- buf = new Buffer(buf, 'utf8');
+TBufferedTransport.prototype.write = function (buf) {
+ if (typeof buf === "string") {
+ buf = new Buffer(buf, "utf8");
}
this.outBuffers.push(buf);
this.outCount += buf.length;
};
-TBufferedTransport.prototype.flush = function() {
+TBufferedTransport.prototype.flush = function () {
// If the seqid of the callback is available pass it to the onFlush
// Then remove the current seqid
var seqid = this._seqid;
@@ -171,8 +174,8 @@
}
var msg = new Buffer(this.outCount),
- pos = 0;
- this.outBuffers.forEach(function(buf) {
+ pos = 0;
+ this.outBuffers.forEach(function (buf) {
buf.copy(msg, pos, 0);
pos += buf.length;
});
@@ -184,4 +187,4 @@
this.outBuffers = [];
this.outCount = 0;
-}
+};
diff --git a/lib/nodejs/lib/thrift/compact_protocol.js b/lib/nodejs/lib/thrift/compact_protocol.js
index 302a88d..e946dc8 100644
--- a/lib/nodejs/lib/thrift/compact_protocol.js
+++ b/lib/nodejs/lib/thrift/compact_protocol.js
@@ -17,9 +17,9 @@
* under the License.
*/
-var log = require('./log');
-var Int64 = require('node-int64');
-var Thrift = require('./thrift');
+var log = require("./log");
+var Int64 = require("node-int64");
+var Thrift = require("./thrift");
var Type = Thrift.Type;
module.exports = TCompactProtocol;
@@ -50,59 +50,58 @@
this.container_limit_ = 0;
this.booleanField_ = {
name: null,
- hasBoolValue: false
+ hasBoolValue: false,
};
this.boolValue_ = {
hasBoolValue: false,
- boolValue: false
+ boolValue: false,
};
-};
-
+}
//
// Compact Protocol Constants
//
/**
- * Compact Protocol ID number.
- * @readonly
- * @const {number} PROTOCOL_ID
- */
-TCompactProtocol.PROTOCOL_ID = -126; //1000 0010
+ * Compact Protocol ID number.
+ * @readonly
+ * @const {number} PROTOCOL_ID
+ */
+TCompactProtocol.PROTOCOL_ID = -126; //1000 0010
/**
- * Compact Protocol version number.
- * @readonly
- * @const {number} VERSION_N
- */
+ * Compact Protocol version number.
+ * @readonly
+ * @const {number} VERSION_N
+ */
TCompactProtocol.VERSION_N = 1;
/**
- * Compact Protocol version mask for combining protocol version and message type in one byte.
- * @readonly
- * @const {number} VERSION_MASK
- */
+ * Compact Protocol version mask for combining protocol version and message type in one byte.
+ * @readonly
+ * @const {number} VERSION_MASK
+ */
TCompactProtocol.VERSION_MASK = 0x1f; //0001 1111
/**
- * Compact Protocol message type mask for combining protocol version and message type in one byte.
- * @readonly
- * @const {number} TYPE_MASK
- */
-TCompactProtocol.TYPE_MASK = -32; //1110 0000
+ * Compact Protocol message type mask for combining protocol version and message type in one byte.
+ * @readonly
+ * @const {number} TYPE_MASK
+ */
+TCompactProtocol.TYPE_MASK = -32; //1110 0000
/**
- * Compact Protocol message type bits for ensuring message type bit size.
- * @readonly
- * @const {number} TYPE_BITS
- */
+ * Compact Protocol message type bits for ensuring message type bit size.
+ * @readonly
+ * @const {number} TYPE_BITS
+ */
TCompactProtocol.TYPE_BITS = 7; //0000 0111
/**
- * Compact Protocol message type shift amount for combining protocol version and message type in one byte.
- * @readonly
- * @const {number} TYPE_SHIFT_AMOUNT
- */
+ * Compact Protocol message type shift amount for combining protocol version and message type in one byte.
+ * @readonly
+ * @const {number} TYPE_SHIFT_AMOUNT
+ */
TCompactProtocol.TYPE_SHIFT_AMOUNT = 5;
/**
@@ -123,19 +122,19 @@
* @property {number} CT_STRUCT - A multifield type.
*/
TCompactProtocol.Types = {
- CT_STOP: 0x00,
- CT_BOOLEAN_TRUE: 0x01,
- CT_BOOLEAN_FALSE: 0x02,
- CT_BYTE: 0x03,
- CT_I16: 0x04,
- CT_I32: 0x05,
- CT_I64: 0x06,
- CT_DOUBLE: 0x07,
- CT_BINARY: 0x08,
- CT_LIST: 0x09,
- CT_SET: 0x0A,
- CT_MAP: 0x0B,
- CT_STRUCT: 0x0C
+ CT_STOP: 0x00,
+ CT_BOOLEAN_TRUE: 0x01,
+ CT_BOOLEAN_FALSE: 0x02,
+ CT_BYTE: 0x03,
+ CT_I16: 0x04,
+ CT_I32: 0x05,
+ CT_I64: 0x06,
+ CT_DOUBLE: 0x07,
+ CT_BINARY: 0x08,
+ CT_LIST: 0x09,
+ CT_SET: 0x0a,
+ CT_MAP: 0x0b,
+ CT_STRUCT: 0x0c,
};
/**
@@ -143,25 +142,24 @@
* @readonly
*/
TCompactProtocol.TTypeToCType = [
- TCompactProtocol.Types.CT_STOP, // T_STOP
- 0, // unused
+ TCompactProtocol.Types.CT_STOP, // T_STOP
+ 0, // unused
TCompactProtocol.Types.CT_BOOLEAN_TRUE, // T_BOOL
- TCompactProtocol.Types.CT_BYTE, // T_BYTE
- TCompactProtocol.Types.CT_DOUBLE, // T_DOUBLE
- 0, // unused
- TCompactProtocol.Types.CT_I16, // T_I16
- 0, // unused
- TCompactProtocol.Types.CT_I32, // T_I32
- 0, // unused
- TCompactProtocol.Types.CT_I64, // T_I64
- TCompactProtocol.Types.CT_BINARY, // T_STRING
- TCompactProtocol.Types.CT_STRUCT, // T_STRUCT
- TCompactProtocol.Types.CT_MAP, // T_MAP
- TCompactProtocol.Types.CT_SET, // T_SET
- TCompactProtocol.Types.CT_LIST, // T_LIST
+ TCompactProtocol.Types.CT_BYTE, // T_BYTE
+ TCompactProtocol.Types.CT_DOUBLE, // T_DOUBLE
+ 0, // unused
+ TCompactProtocol.Types.CT_I16, // T_I16
+ 0, // unused
+ TCompactProtocol.Types.CT_I32, // T_I32
+ 0, // unused
+ TCompactProtocol.Types.CT_I64, // T_I64
+ TCompactProtocol.Types.CT_BINARY, // T_STRING
+ TCompactProtocol.Types.CT_STRUCT, // T_STRUCT
+ TCompactProtocol.Types.CT_MAP, // T_MAP
+ TCompactProtocol.Types.CT_SET, // T_SET
+ TCompactProtocol.Types.CT_LIST, // T_LIST
];
-
//
// Compact Protocol Utilities
//
@@ -169,7 +167,7 @@
/**
* Returns the underlying transport layer.
* @return {object} The underlying transport layer.
- */TCompactProtocol.prototype.getTransport = function() {
+ */ TCompactProtocol.prototype.getTransport = function () {
return this.trans;
};
@@ -179,7 +177,7 @@
* @param {number} ttype - Thrift type value
* @returns {number} Compact protocol type value
*/
-TCompactProtocol.prototype.getCompactType = function(ttype) {
+TCompactProtocol.prototype.getCompactType = function (ttype) {
return TCompactProtocol.TTypeToCType[ttype];
};
@@ -189,7 +187,7 @@
* @param {number} type - Compact Protocol type value
* @returns {number} Thrift Type value
*/
-TCompactProtocol.prototype.getTType = function(type) {
+TCompactProtocol.prototype.getTType = function (type) {
switch (type) {
case Type.STOP:
return Type.STOP;
@@ -217,12 +215,14 @@
case TCompactProtocol.Types.CT_STRUCT:
return Type.STRUCT;
default:
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Unknown type: " + type);
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.INVALID_DATA,
+ "Unknown type: " + type,
+ );
}
return Type.STOP;
};
-
//
// Compact Protocol write operations
//
@@ -230,7 +230,7 @@
/**
* Send any buffered bytes to the end point.
*/
-TCompactProtocol.prototype.flush = function() {
+TCompactProtocol.prototype.flush = function () {
return this.trans.flush();
};
@@ -240,31 +240,33 @@
* @param {number} type - The type of message (CALL, REPLY, EXCEPTION, ONEWAY).
* @param {number} seqid - The call sequence number (if any).
*/
-TCompactProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
+TCompactProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
this.writeByte(TCompactProtocol.PROTOCOL_ID);
- this.writeByte((TCompactProtocol.VERSION_N & TCompactProtocol.VERSION_MASK) |
- ((type << TCompactProtocol.TYPE_SHIFT_AMOUNT) & TCompactProtocol.TYPE_MASK));
+ this.writeByte(
+ (TCompactProtocol.VERSION_N & TCompactProtocol.VERSION_MASK) |
+ ((type << TCompactProtocol.TYPE_SHIFT_AMOUNT) &
+ TCompactProtocol.TYPE_MASK),
+ );
this.writeVarint32(seqid);
this.writeString(name);
// Record client seqid to find callback again
if (this._seqid) {
- log.warning('SeqId already set', { 'name': name });
+ log.warning("SeqId already set", { name: name });
} else {
this._seqid = seqid;
this.trans.setCurrSeqId(seqid);
}
};
-TCompactProtocol.prototype.writeMessageEnd = function() {
-};
+TCompactProtocol.prototype.writeMessageEnd = function () {};
-TCompactProtocol.prototype.writeStructBegin = function(name) {
+TCompactProtocol.prototype.writeStructBegin = function (name) {
this.lastField_.push(this.lastFieldId_);
this.lastFieldId_ = 0;
};
-TCompactProtocol.prototype.writeStructEnd = function() {
+TCompactProtocol.prototype.writeStructEnd = function () {
this.lastFieldId_ = this.lastField_.pop();
};
@@ -274,7 +276,7 @@
* @param {number} type - The field data type (a normal Thrift field Type).
* @param {number} id - The IDL field Id.
*/
-TCompactProtocol.prototype.writeFieldBegin = function(name, type, id) {
+TCompactProtocol.prototype.writeFieldBegin = function (name, type, id) {
if (type != Type.BOOL) {
return this.writeFieldBeginInternal(name, type, id, -1);
}
@@ -284,10 +286,9 @@
this.booleanField_.fieldId = id;
};
-TCompactProtocol.prototype.writeFieldEnd = function() {
-};
+TCompactProtocol.prototype.writeFieldEnd = function () {};
-TCompactProtocol.prototype.writeFieldStop = function() {
+TCompactProtocol.prototype.writeFieldStop = function () {
this.writeByte(TCompactProtocol.Types.CT_STOP);
};
@@ -297,80 +298,85 @@
* @param {number} valType - The Thrift type of the map values.
* @param {number} size - The number of k/v pairs in the map.
*/
-TCompactProtocol.prototype.writeMapBegin = function(keyType, valType, size) {
+TCompactProtocol.prototype.writeMapBegin = function (keyType, valType, size) {
if (size === 0) {
this.writeByte(0);
} else {
this.writeVarint32(size);
- this.writeByte(this.getCompactType(keyType) << 4 | this.getCompactType(valType));
+ this.writeByte(
+ (this.getCompactType(keyType) << 4) | this.getCompactType(valType),
+ );
}
};
-TCompactProtocol.prototype.writeMapEnd = function() {
-};
+TCompactProtocol.prototype.writeMapEnd = function () {};
/**
* Writes a list collection header
* @param {number} elemType - The Thrift type of the list elements.
* @param {number} size - The number of elements in the list.
*/
-TCompactProtocol.prototype.writeListBegin = function(elemType, size) {
+TCompactProtocol.prototype.writeListBegin = function (elemType, size) {
this.writeCollectionBegin(elemType, size);
};
-TCompactProtocol.prototype.writeListEnd = function() {
-};
+TCompactProtocol.prototype.writeListEnd = function () {};
/**
* Writes a set collection header
* @param {number} elemType - The Thrift type of the set elements.
* @param {number} size - The number of elements in the set.
*/
-TCompactProtocol.prototype.writeSetBegin = function(elemType, size) {
+TCompactProtocol.prototype.writeSetBegin = function (elemType, size) {
this.writeCollectionBegin(elemType, size);
};
-TCompactProtocol.prototype.writeSetEnd = function() {
-};
+TCompactProtocol.prototype.writeSetEnd = function () {};
-TCompactProtocol.prototype.writeBool = function(value) {
+TCompactProtocol.prototype.writeBool = function (value) {
if (this.booleanField_.name !== null) {
// we haven't written the field header yet
- this.writeFieldBeginInternal(this.booleanField_.name,
- this.booleanField_.fieldType,
- this.booleanField_.fieldId,
- (value ? TCompactProtocol.Types.CT_BOOLEAN_TRUE
- : TCompactProtocol.Types.CT_BOOLEAN_FALSE));
+ this.writeFieldBeginInternal(
+ this.booleanField_.name,
+ this.booleanField_.fieldType,
+ this.booleanField_.fieldId,
+ value
+ ? TCompactProtocol.Types.CT_BOOLEAN_TRUE
+ : TCompactProtocol.Types.CT_BOOLEAN_FALSE,
+ );
this.booleanField_.name = null;
} else {
// we're not part of a field, so just write the value
- this.writeByte((value ? TCompactProtocol.Types.CT_BOOLEAN_TRUE
- : TCompactProtocol.Types.CT_BOOLEAN_FALSE));
+ this.writeByte(
+ value
+ ? TCompactProtocol.Types.CT_BOOLEAN_TRUE
+ : TCompactProtocol.Types.CT_BOOLEAN_FALSE,
+ );
}
};
-TCompactProtocol.prototype.writeByte = function(b) {
+TCompactProtocol.prototype.writeByte = function (b) {
this.trans.write(new Buffer([b]));
};
-TCompactProtocol.prototype.writeI16 = function(i16) {
+TCompactProtocol.prototype.writeI16 = function (i16) {
this.writeVarint32(this.i32ToZigzag(i16));
};
-TCompactProtocol.prototype.writeI32 = function(i32) {
+TCompactProtocol.prototype.writeI32 = function (i32) {
this.writeVarint32(this.i32ToZigzag(i32));
};
-TCompactProtocol.prototype.writeI64 = function(i64) {
+TCompactProtocol.prototype.writeI64 = function (i64) {
this.writeVarint64(this.i64ToZigzag(i64));
};
// Little-endian, unlike TBinaryProtocol
-TCompactProtocol.prototype.writeDouble = function(v) {
+TCompactProtocol.prototype.writeDouble = function (v) {
var buff = new Buffer(8);
var m, e, c;
- buff[7] = (v < 0 ? 0x80 : 0x00);
+ buff[7] = v < 0 ? 0x80 : 0x00;
v = Math.abs(v);
if (v !== v) {
@@ -388,22 +394,17 @@
c *= 2;
}
- if (e + 1023 >= 2047)
- {
+ if (e + 1023 >= 2047) {
// Overflow
m = 0;
e = 2047;
- }
- else if (e + 1023 >= 1)
- {
+ } else if (e + 1023 >= 1) {
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
- m = (v*c-1) * POW_52;
+ m = (v * c - 1) * POW_52;
e += 1023;
- }
- else
- {
+ } else {
// Denormalized - also catches the '0' case, somewhat by chance
- m = (v * POW_1022) * POW_52;
+ m = v * POW_1022 * POW_52;
e = 0;
}
}
@@ -428,45 +429,53 @@
this.trans.write(buff);
};
-TCompactProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) {
- if (typeof arg === 'string') {
- this.writeVarint32(Buffer.byteLength(arg, encoding)) ;
+TCompactProtocol.prototype.writeStringOrBinary = function (
+ name,
+ encoding,
+ arg,
+) {
+ if (typeof arg === "string") {
+ this.writeVarint32(Buffer.byteLength(arg, encoding));
this.trans.write(new Buffer(arg, encoding));
- } else if (arg instanceof Buffer ||
- Object.prototype.toString.call(arg) == '[object Uint8Array]') {
+ } else if (
+ arg instanceof Buffer ||
+ Object.prototype.toString.call(arg) == "[object Uint8Array]"
+ ) {
// Buffers in Node.js under Browserify may extend UInt8Array instead of
// defining a new object. We detect them here so we can write them
// correctly
this.writeVarint32(arg.length);
this.trans.write(arg);
} else {
- throw new Error(name + ' called without a string/Buffer argument: ' + arg);
+ throw new Error(name + " called without a string/Buffer argument: " + arg);
}
};
-TCompactProtocol.prototype.writeString = function(arg) {
- this.writeStringOrBinary('writeString', 'utf8', arg);
+TCompactProtocol.prototype.writeString = function (arg) {
+ this.writeStringOrBinary("writeString", "utf8", arg);
};
-TCompactProtocol.prototype.writeBinary = function(arg) {
- this.writeStringOrBinary('writeBinary', 'binary', arg);
+TCompactProtocol.prototype.writeBinary = function (arg) {
+ this.writeStringOrBinary("writeBinary", "binary", arg);
};
-
//
// Compact Protocol internal write methods
//
-TCompactProtocol.prototype.writeFieldBeginInternal = function(name,
- fieldType,
- fieldId,
- typeOverride) {
+TCompactProtocol.prototype.writeFieldBeginInternal = function (
+ name,
+ fieldType,
+ fieldId,
+ typeOverride,
+) {
//If there's a type override, use that.
- var typeToWrite = (typeOverride == -1 ? this.getCompactType(fieldType) : typeOverride);
+ var typeToWrite =
+ typeOverride == -1 ? this.getCompactType(fieldType) : typeOverride;
//Check if we can delta encode the field id
if (fieldId > this.lastFieldId_ && fieldId - this.lastFieldId_ <= 15) {
//Include the type delta with the field ID
- this.writeByte((fieldId - this.lastFieldId_) << 4 | typeToWrite);
+ this.writeByte(((fieldId - this.lastFieldId_) << 4) | typeToWrite);
} else {
//Write separate type and ID values
this.writeByte(typeToWrite);
@@ -475,10 +484,10 @@
this.lastFieldId_ = fieldId;
};
-TCompactProtocol.prototype.writeCollectionBegin = function(elemType, size) {
+TCompactProtocol.prototype.writeCollectionBegin = function (elemType, size) {
if (size <= 14) {
//Combine size and type in one byte if possible
- this.writeByte(size << 4 | this.getCompactType(elemType));
+ this.writeByte((size << 4) | this.getCompactType(elemType));
} else {
this.writeByte(0xf0 | this.getCompactType(elemType));
this.writeVarint32(size);
@@ -488,20 +497,20 @@
/**
* Write an i32 as a varint. Results in 1-5 bytes on the wire.
*/
-TCompactProtocol.prototype.writeVarint32 = function(n) {
+TCompactProtocol.prototype.writeVarint32 = function (n) {
var buf = new Buffer(5);
var wsize = 0;
while (true) {
- if ((n & ~0x7F) === 0) {
+ if ((n & ~0x7f) === 0) {
buf[wsize++] = n;
break;
} else {
- buf[wsize++] = ((n & 0x7F) | 0x80);
+ buf[wsize++] = (n & 0x7f) | 0x80;
n = n >>> 7;
}
}
var wbuf = new Buffer(wsize);
- buf.copy(wbuf,0,0,wsize);
+ buf.copy(wbuf, 0, 0, wsize);
this.trans.write(wbuf);
};
@@ -509,12 +518,15 @@
* Write an i64 as a varint. Results in 1-10 bytes on the wire.
* N.B. node-int64 is always big endian
*/
-TCompactProtocol.prototype.writeVarint64 = function(n) {
- if (typeof n === "number"){
+TCompactProtocol.prototype.writeVarint64 = function (n) {
+ if (typeof n === "number") {
n = new Int64(n);
}
- if (! (n instanceof Int64)) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Expected Int64 or Number, found: " + n);
+ if (!(n instanceof Int64)) {
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.INVALID_DATA,
+ "Expected Int64 or Number, found: " + n,
+ );
}
var buf = new Buffer(10);
@@ -523,11 +535,11 @@
var lo = n.buffer.readUInt32BE(4, true);
var mask = 0;
while (true) {
- if (((lo & ~0x7F) === 0) && (hi === 0)) {
+ if ((lo & ~0x7f) === 0 && hi === 0) {
buf[wsize++] = lo;
break;
} else {
- buf[wsize++] = ((lo & 0x7F) | 0x80);
+ buf[wsize++] = (lo & 0x7f) | 0x80;
mask = hi << 25;
lo = lo >>> 7;
hi = hi >>> 7;
@@ -535,7 +547,7 @@
}
}
var wbuf = new Buffer(wsize);
- buf.copy(wbuf,0,0,wsize);
+ buf.copy(wbuf, 0, 0, wsize);
this.trans.write(wbuf);
};
@@ -543,20 +555,23 @@
* Convert l into a zigzag long. This allows negative numbers to be
* represented compactly as a varint.
*/
-TCompactProtocol.prototype.i64ToZigzag = function(l) {
- if (typeof l === 'string') {
+TCompactProtocol.prototype.i64ToZigzag = function (l) {
+ if (typeof l === "string") {
l = new Int64(parseInt(l, 10));
- } else if (typeof l === 'number') {
+ } else if (typeof l === "number") {
l = new Int64(l);
}
- if (! (l instanceof Int64)) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Expected Int64 or Number, found: " + l);
+ if (!(l instanceof Int64)) {
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.INVALID_DATA,
+ "Expected Int64 or Number, found: " + l,
+ );
}
var hi = l.buffer.readUInt32BE(0, true);
var lo = l.buffer.readUInt32BE(4, true);
var sign = hi >>> 31;
- hi = ((hi << 1) | (lo >>> 31)) ^ ((!!sign) ? 0xFFFFFFFF : 0);
- lo = (lo << 1) ^ ((!!sign) ? 0xFFFFFFFF : 0);
+ hi = ((hi << 1) | (lo >>> 31)) ^ (!!sign ? 0xffffffff : 0);
+ lo = (lo << 1) ^ (!!sign ? 0xffffffff : 0);
return new Int64(hi, lo);
};
@@ -564,29 +579,36 @@
* Convert n into a zigzag int. This allows negative numbers to be
* represented compactly as a varint.
*/
-TCompactProtocol.prototype.i32ToZigzag = function(n) {
- return (n << 1) ^ ((n & 0x80000000) ? 0xFFFFFFFF : 0);
+TCompactProtocol.prototype.i32ToZigzag = function (n) {
+ return (n << 1) ^ (n & 0x80000000 ? 0xffffffff : 0);
};
-
//
// Compact Protocol read operations
//
-TCompactProtocol.prototype.readMessageBegin = function() {
+TCompactProtocol.prototype.readMessageBegin = function () {
//Read protocol ID
var protocolId = this.trans.readByte();
if (protocolId != TCompactProtocol.PROTOCOL_ID) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad protocol identifier " + protocolId);
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.BAD_VERSION,
+ "Bad protocol identifier " + protocolId,
+ );
}
//Read Version and Type
var versionAndType = this.trans.readByte();
- var version = (versionAndType & TCompactProtocol.VERSION_MASK);
+ var version = versionAndType & TCompactProtocol.VERSION_MASK;
if (version != TCompactProtocol.VERSION_N) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad protocol version " + version);
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.BAD_VERSION,
+ "Bad protocol version " + version,
+ );
}
- var type = ((versionAndType >> TCompactProtocol.TYPE_SHIFT_AMOUNT) & TCompactProtocol.TYPE_BITS);
+ var type =
+ (versionAndType >> TCompactProtocol.TYPE_SHIFT_AMOUNT) &
+ TCompactProtocol.TYPE_BITS;
//Read SeqId
var seqid = this.readVarint32();
@@ -594,62 +616,65 @@
//Read name
var name = this.readString();
- return {fname: name, mtype: type, rseqid: seqid};
+ return { fname: name, mtype: type, rseqid: seqid };
};
-TCompactProtocol.prototype.readMessageEnd = function() {
-};
+TCompactProtocol.prototype.readMessageEnd = function () {};
-TCompactProtocol.prototype.readStructBegin = function() {
+TCompactProtocol.prototype.readStructBegin = function () {
this.lastField_.push(this.lastFieldId_);
this.lastFieldId_ = 0;
- return {fname: ''};
+ return { fname: "" };
};
-TCompactProtocol.prototype.readStructEnd = function() {
+TCompactProtocol.prototype.readStructEnd = function () {
this.lastFieldId_ = this.lastField_.pop();
};
-TCompactProtocol.prototype.readFieldBegin = function() {
+TCompactProtocol.prototype.readFieldBegin = function () {
var fieldId = 0;
var b = this.trans.readByte(b);
- var type = (b & 0x0f);
+ var type = b & 0x0f;
if (type == TCompactProtocol.Types.CT_STOP) {
- return {fname: null, ftype: Thrift.Type.STOP, fid: 0};
+ return { fname: null, ftype: Thrift.Type.STOP, fid: 0 };
}
//Mask off the 4 MSB of the type header to check for field id delta.
- var modifier = ((b & 0x000000f0) >>> 4);
+ var modifier = (b & 0x000000f0) >>> 4;
if (modifier === 0) {
//If not a delta read the field id.
fieldId = this.readI16();
} else {
//Recover the field id from the delta
- fieldId = (this.lastFieldId_ + modifier);
+ fieldId = this.lastFieldId_ + modifier;
}
var fieldType = this.getTType(type);
//Boolean are encoded with the type
- if (type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ||
- type == TCompactProtocol.Types.CT_BOOLEAN_FALSE) {
+ if (
+ type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ||
+ type == TCompactProtocol.Types.CT_BOOLEAN_FALSE
+ ) {
this.boolValue_.hasBoolValue = true;
this.boolValue_.boolValue =
- (type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ? true : false);
+ type == TCompactProtocol.Types.CT_BOOLEAN_TRUE ? true : false;
}
//Save the new field for the next delta computation.
this.lastFieldId_ = fieldId;
- return {fname: null, ftype: fieldType, fid: fieldId};
+ return { fname: null, ftype: fieldType, fid: fieldId };
};
-TCompactProtocol.prototype.readFieldEnd = function() {
-};
+TCompactProtocol.prototype.readFieldEnd = function () {};
-TCompactProtocol.prototype.readMapBegin = function() {
+TCompactProtocol.prototype.readMapBegin = function () {
var msize = this.readVarint32();
if (msize < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative map size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative map size",
+ );
}
var kvType = 0;
@@ -659,13 +684,12 @@
var keyType = this.getTType((kvType & 0xf0) >>> 4);
var valType = this.getTType(kvType & 0xf);
- return {ktype: keyType, vtype: valType, size: msize};
+ return { ktype: keyType, vtype: valType, size: msize };
};
-TCompactProtocol.prototype.readMapEnd = function() {
-};
+TCompactProtocol.prototype.readMapEnd = function () {};
-TCompactProtocol.prototype.readListBegin = function() {
+TCompactProtocol.prototype.readListBegin = function () {
var size_and_type = this.trans.readByte();
var lsize = (size_and_type >>> 4) & 0x0000000f;
@@ -674,25 +698,26 @@
}
if (lsize < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative list size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative list size",
+ );
}
var elemType = this.getTType(size_and_type & 0x0000000f);
- return {etype: elemType, size: lsize};
+ return { etype: elemType, size: lsize };
};
-TCompactProtocol.prototype.readListEnd = function() {
-};
+TCompactProtocol.prototype.readListEnd = function () {};
-TCompactProtocol.prototype.readSetBegin = function() {
+TCompactProtocol.prototype.readSetBegin = function () {
return this.readListBegin();
};
-TCompactProtocol.prototype.readSetEnd = function() {
-};
+TCompactProtocol.prototype.readSetEnd = function () {};
-TCompactProtocol.prototype.readBool = function() {
+TCompactProtocol.prototype.readBool = function () {
var value = false;
var rsize = 0;
if (this.boolValue_.hasBoolValue === true) {
@@ -701,50 +726,50 @@
} else {
var res = this.trans.readByte();
rsize = res.rsize;
- value = (res.value == TCompactProtocol.Types.CT_BOOLEAN_TRUE);
+ value = res.value == TCompactProtocol.Types.CT_BOOLEAN_TRUE;
}
return value;
};
-TCompactProtocol.prototype.readByte = function() {
+TCompactProtocol.prototype.readByte = function () {
return this.trans.readByte();
};
-TCompactProtocol.prototype.readI16 = function() {
+TCompactProtocol.prototype.readI16 = function () {
return this.readI32();
};
-TCompactProtocol.prototype.readI32 = function() {
+TCompactProtocol.prototype.readI32 = function () {
return this.zigzagToI32(this.readVarint32());
};
-TCompactProtocol.prototype.readI64 = function() {
+TCompactProtocol.prototype.readI64 = function () {
return this.zigzagToI64(this.readVarint64());
};
// Little-endian, unlike TBinaryProtocol
-TCompactProtocol.prototype.readDouble = function() {
+TCompactProtocol.prototype.readDouble = function () {
var buff = this.trans.read(8);
var off = 0;
var signed = buff[off + 7] & 0x80;
- var e = (buff[off+6] & 0xF0) >> 4;
- e += (buff[off+7] & 0x7F) << 4;
+ var e = (buff[off + 6] & 0xf0) >> 4;
+ e += (buff[off + 7] & 0x7f) << 4;
var m = buff[off];
- m += buff[off+1] << 8;
- m += buff[off+2] << 16;
- m += buff[off+3] * POW_24;
- m += buff[off+4] * POW_32;
- m += buff[off+5] * POW_40;
- m += (buff[off+6] & 0x0F) * POW_48;
+ m += buff[off + 1] << 8;
+ m += buff[off + 2] << 16;
+ m += buff[off + 3] * POW_24;
+ m += buff[off + 4] * POW_32;
+ m += buff[off + 5] * POW_40;
+ m += (buff[off + 6] & 0x0f) * POW_48;
switch (e) {
case 0:
e = -1022;
break;
case 2047:
- return m ? NaN : (signed ? -Infinity : Infinity);
+ return m ? NaN : signed ? -Infinity : Infinity;
default:
m += POW_52;
e -= 1023;
@@ -757,19 +782,22 @@
return m * Math.pow(2, e - 52);
};
-TCompactProtocol.prototype.readBinary = function() {
+TCompactProtocol.prototype.readBinary = function () {
var size = this.readVarint32();
if (size === 0) {
return new Buffer(0);
}
if (size < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative binary size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative binary size",
+ );
}
return this.trans.read(size);
};
-TCompactProtocol.prototype.readString = function() {
+TCompactProtocol.prototype.readString = function () {
var size = this.readVarint32();
// Catch empty string case
if (size === 0) {
@@ -778,12 +806,14 @@
// Catch error cases
if (size < 0) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative string size");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.NEGATIVE_SIZE,
+ "Negative string size",
+ );
}
return this.trans.readString(size);
};
-
//
// Compact Protocol internal read operations
//
@@ -792,7 +822,7 @@
* Read an i32 from the wire as a varint. The MSB of each byte is set
* if there is another byte to follow. This can read up to 5 bytes.
*/
-TCompactProtocol.prototype.readVarint32 = function() {
+TCompactProtocol.prototype.readVarint32 = function () {
return this.readVarint64().toNumber();
};
@@ -800,28 +830,31 @@
* Read an i64 from the wire as a proper varint. The MSB of each byte is set
* if there is another byte to follow. This can read up to 10 bytes.
*/
-TCompactProtocol.prototype.readVarint64 = function() {
+TCompactProtocol.prototype.readVarint64 = function () {
var rsize = 0;
var lo = 0;
var hi = 0;
var shift = 0;
while (true) {
var b = this.trans.readByte();
- rsize ++;
+ rsize++;
if (shift <= 25) {
lo = lo | ((b & 0x7f) << shift);
} else if (25 < shift && shift < 32) {
lo = lo | ((b & 0x7f) << shift);
- hi = hi | ((b & 0x7f) >>> (32-shift));
+ hi = hi | ((b & 0x7f) >>> (32 - shift));
} else {
- hi = hi | ((b & 0x7f) << (shift-32));
+ hi = hi | ((b & 0x7f) << (shift - 32));
}
shift += 7;
if (!(b & 0x80)) {
break;
}
if (rsize >= 10) {
- throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.INVALID_DATA, "Variable-length int over 10 bytes.");
+ throw new Thrift.TProtocolException(
+ Thrift.TProtocolExceptionType.INVALID_DATA,
+ "Variable-length int over 10 bytes.",
+ );
}
}
return new Int64(hi, lo);
@@ -830,14 +863,14 @@
/**
* Convert from zigzag int to int.
*/
-TCompactProtocol.prototype.zigzagToI32 = function(n) {
+TCompactProtocol.prototype.zigzagToI32 = function (n) {
return (n >>> 1) ^ (-1 * (n & 1));
};
/**
* Convert from zigzag long to long.
*/
-TCompactProtocol.prototype.zigzagToI64 = function(n) {
+TCompactProtocol.prototype.zigzagToI64 = function (n) {
var hi = n.buffer.readUInt32BE(0, true);
var lo = n.buffer.readUInt32BE(4, true);
@@ -846,13 +879,13 @@
var hi_neg = neg.buffer.readUInt32BE(0, true);
var lo_neg = neg.buffer.readUInt32BE(4, true);
- var hi_lo = (hi << 31);
- hi = (hi >>> 1) ^ (hi_neg);
- lo = ((lo >>> 1) | hi_lo) ^ (lo_neg);
+ var hi_lo = hi << 31;
+ hi = (hi >>> 1) ^ hi_neg;
+ lo = ((lo >>> 1) | hi_lo) ^ lo_neg;
return new Int64(hi, lo);
};
-TCompactProtocol.prototype.skip = function(type) {
+TCompactProtocol.prototype.skip = function (type) {
switch (type) {
case Type.BOOL:
this.readBool();
@@ -910,6 +943,6 @@
this.readListEnd();
break;
default:
- throw new Error("Invalid type: " + type);
+ throw new Error("Invalid type: " + type);
}
};
diff --git a/lib/nodejs/lib/thrift/connection.js b/lib/nodejs/lib/thrift/connection.js
index b4e5a05..dcade80 100644
--- a/lib/nodejs/lib/thrift/connection.js
+++ b/lib/nodejs/lib/thrift/connection.js
@@ -16,29 +16,29 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var EventEmitter = require('events').EventEmitter;
-var constants = require('constants');
-var net = require('net');
-var tls = require('tls');
-var thrift = require('./thrift');
-var log = require('./log');
+var util = require("util");
+var EventEmitter = require("events").EventEmitter;
+var constants = require("constants");
+var net = require("net");
+var tls = require("tls");
+var thrift = require("./thrift");
+var log = require("./log");
-var TBufferedTransport = require('./buffered_transport');
-var TBinaryProtocol = require('./binary_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TBinaryProtocol = require("./binary_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
-var createClient = require('./create_client');
+var createClient = require("./create_client");
-var binary = require('./binary');
+var binary = require("./binary");
-var Connection = exports.Connection = function(stream, options) {
+var Connection = (exports.Connection = function (stream, options) {
var self = this;
EventEmitter.call(this);
this.seqId2Service = {};
this.connection = stream;
- this.ssl = (stream.encrypted);
+ this.ssl = stream.encrypted;
this.options = options || {};
this.transport = this.options.transport || TBufferedTransport;
this.protocol = this.options.protocol || TBinaryProtocol;
@@ -48,123 +48,139 @@
this.initialize_retry_vars();
this._debug = this.options.debug || false;
- if (this.options.max_attempts &&
- !isNaN(this.options.max_attempts) &&
- this.options.max_attempts > 0) {
- this.max_attempts = +this.options.max_attempts;
+ if (
+ this.options.max_attempts &&
+ !isNaN(this.options.max_attempts) &&
+ this.options.max_attempts > 0
+ ) {
+ this.max_attempts = +this.options.max_attempts;
}
this.retry_max_delay = null;
- if (this.options.retry_max_delay !== undefined &&
- !isNaN(this.options.retry_max_delay) &&
- this.options.retry_max_delay > 0) {
- this.retry_max_delay = this.options.retry_max_delay;
+ if (
+ this.options.retry_max_delay !== undefined &&
+ !isNaN(this.options.retry_max_delay) &&
+ this.options.retry_max_delay > 0
+ ) {
+ this.retry_max_delay = this.options.retry_max_delay;
}
this.connect_timeout = false;
- if (this.options.connect_timeout &&
- !isNaN(this.options.connect_timeout) &&
- this.options.connect_timeout > 0) {
- this.connect_timeout = +this.options.connect_timeout;
+ if (
+ this.options.connect_timeout &&
+ !isNaN(this.options.connect_timeout) &&
+ this.options.connect_timeout > 0
+ ) {
+ this.connect_timeout = +this.options.connect_timeout;
}
- this.connection.addListener(this.ssl ? "secureConnect" : "connect", function() {
- self.connected = true;
+ this.connection.addListener(
+ this.ssl ? "secureConnect" : "connect",
+ function () {
+ self.connected = true;
- this.setTimeout(self.options.timeout || 0);
- this.setNoDelay();
- this.frameLeft = 0;
- this.framePos = 0;
- this.frame = null;
- self.initialize_retry_vars();
- self.flush_offline_queue();
+ this.setTimeout(self.options.timeout || 0);
+ this.setNoDelay();
+ this.frameLeft = 0;
+ this.framePos = 0;
+ this.frame = null;
+ self.initialize_retry_vars();
+ self.flush_offline_queue();
- self.emit("connect");
- });
+ self.emit("connect");
+ },
+ );
- this.connection.addListener("error", function(err) {
+ this.connection.addListener("error", function (err) {
// Only emit the error if no-one else is listening on the connection
// or if someone is listening on us, because Node turns unhandled
// 'error' events into exceptions.
- if (self.connection.listeners('error').length === 1 ||
- self.listeners('error').length > 0) {
+ if (
+ self.connection.listeners("error").length === 1 ||
+ self.listeners("error").length > 0
+ ) {
self.emit("error", err);
}
});
// Add a close listener
- this.connection.addListener("close", function() {
+ this.connection.addListener("close", function () {
self.connection_gone(); // handle close event. try to reconnect
});
- this.connection.addListener("timeout", function() {
+ this.connection.addListener("timeout", function () {
self.emit("timeout");
});
- this.connection.addListener("data", self.transport.receiver(function(transport_with_data) {
- var message = new self.protocol(transport_with_data);
- try {
- while (true) {
- var header = message.readMessageBegin();
- var dummy_seqid = header.rseqid * -1;
- var client = self.client;
- //The Multiplexed Protocol stores a hash of seqid to service names
- // in seqId2Service. If the SeqId is found in the hash we need to
- // lookup the appropriate client for this call.
- // The connection.client object is a single client object when not
- // multiplexing, when using multiplexing it is a service name keyed
- // hash of client objects.
- //NOTE: The 2 way interdependencies between protocols, transports,
- // connections and clients in the Node.js implementation are irregular
- // and make the implementation difficult to extend and maintain. We
- // should bring this stuff inline with typical thrift I/O stack
- // operation soon.
- // --ra
- var service_name = self.seqId2Service[header.rseqid];
- if (service_name) {
- client = self.client[service_name];
- }
- /*jshint -W083 */
- client._reqs[dummy_seqid] = function(err, success){
- transport_with_data.commitPosition();
-
- var callback = client._reqs[header.rseqid];
- delete client._reqs[header.rseqid];
+ this.connection.addListener(
+ "data",
+ self.transport.receiver(function (transport_with_data) {
+ var message = new self.protocol(transport_with_data);
+ try {
+ while (true) {
+ var header = message.readMessageBegin();
+ var dummy_seqid = header.rseqid * -1;
+ var client = self.client;
+ //The Multiplexed Protocol stores a hash of seqid to service names
+ // in seqId2Service. If the SeqId is found in the hash we need to
+ // lookup the appropriate client for this call.
+ // The connection.client object is a single client object when not
+ // multiplexing, when using multiplexing it is a service name keyed
+ // hash of client objects.
+ //NOTE: The 2 way interdependencies between protocols, transports,
+ // connections and clients in the Node.js implementation are irregular
+ // and make the implementation difficult to extend and maintain. We
+ // should bring this stuff inline with typical thrift I/O stack
+ // operation soon.
+ // --ra
+ var service_name = self.seqId2Service[header.rseqid];
if (service_name) {
- delete self.seqId2Service[header.rseqid];
+ client = self.client[service_name];
}
- if (callback) {
- callback(err, success);
- }
- };
- /*jshint +W083 */
+ /*jshint -W083 */
+ client._reqs[dummy_seqid] = function (err, success) {
+ transport_with_data.commitPosition();
- if(client['recv_' + header.fname]) {
- client['recv_' + header.fname](message, header.mtype, dummy_seqid);
+ var callback = client._reqs[header.rseqid];
+ delete client._reqs[header.rseqid];
+ if (service_name) {
+ delete self.seqId2Service[header.rseqid];
+ }
+ if (callback) {
+ callback(err, success);
+ }
+ };
+ /*jshint +W083 */
+
+ if (client["recv_" + header.fname]) {
+ client["recv_" + header.fname](message, header.mtype, dummy_seqid);
+ } else {
+ delete client._reqs[dummy_seqid];
+ self.emit(
+ "error",
+ new thrift.TApplicationException(
+ thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
+ "Received a response to an unknown RPC function",
+ ),
+ );
+ }
+ }
+ } catch (e) {
+ if (e instanceof InputBufferUnderrunError) {
+ transport_with_data.rollbackPosition();
} else {
- delete client._reqs[dummy_seqid];
- self.emit("error",
- new thrift.TApplicationException(thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
- "Received a response to an unknown RPC function"));
+ self.emit("error", e);
}
}
- }
- catch (e) {
- if (e instanceof InputBufferUnderrunError) {
- transport_with_data.rollbackPosition();
- }
- else {
- self.emit('error', e);
- }
- }
- }));
-};
+ }),
+ );
+});
util.inherits(Connection, EventEmitter);
-Connection.prototype.end = function() {
+Connection.prototype.end = function () {
this.forceClose = true;
this.connection.end();
};
-Connection.prototype.destroy = function() {
+Connection.prototype.destroy = function () {
this.connection.destroy();
};
@@ -183,12 +199,12 @@
// Reset offline queue
this.offline_queue = [];
// Attempt to write queued items
- offline_queue.forEach(function(data) {
+ offline_queue.forEach(function (data) {
self.write(data);
});
};
-Connection.prototype.write = function(data) {
+Connection.prototype.write = function (data) {
if (!this.connected) {
this.offline_queue.push(data);
return;
@@ -201,7 +217,7 @@
this.connected = false;
// If closed by manual, emit close event and cancel reconnect process
- if(this.forceClose) {
+ if (this.forceClose) {
if (this.retry_timer) {
clearTimeout(this.retry_timer);
this.retry_timer = null;
@@ -220,7 +236,10 @@
return;
}
- if (this.retry_max_delay !== null && this.retry_delay >= this.retry_max_delay) {
+ if (
+ this.retry_max_delay !== null &&
+ this.retry_delay >= this.retry_max_delay
+ ) {
this.retry_delay = this.retry_max_delay;
} else {
this.retry_delay = Math.floor(this.retry_delay * this.retry_backoff);
@@ -230,7 +249,11 @@
if (this.max_attempts && this.attempts >= this.max_attempts) {
this.retry_timer = null;
- console.error("thrift: Couldn't get thrift connection after " + this.max_attempts + " attempts.");
+ console.error(
+ "thrift: Couldn't get thrift connection after " +
+ this.max_attempts +
+ " attempts.",
+ );
self.emit("close");
return;
}
@@ -238,7 +261,7 @@
this.attempts += 1;
this.emit("reconnecting", {
delay: self.retry_delay,
- attempt: self.attempts
+ attempt: self.attempts,
});
this.retry_timer = setTimeout(function () {
@@ -247,10 +270,14 @@
self.retry_totaltime += self.retry_delay;
if (self.connect_timeout && self.retry_totaltime >= self.connect_timeout) {
- self.retry_timer = null;
- console.error("thrift: Couldn't get thrift connection after " + self.retry_totaltime + "ms.");
- self.emit("close");
- return;
+ self.retry_timer = null;
+ console.error(
+ "thrift: Couldn't get thrift connection after " +
+ self.retry_totaltime +
+ "ms.",
+ );
+ self.emit("close");
+ return;
}
if (self.path !== undefined) {
@@ -262,11 +289,11 @@
}, this.retry_delay);
};
-exports.createConnection = function(host, port, options) {
- var stream = net.createConnection( {
+exports.createConnection = function (host, port, options) {
+ var stream = net.createConnection({
port: port,
host: host,
- timeout: options.connect_timeout || options.timeout || 0
+ timeout: options.connect_timeout || options.timeout || 0,
});
var connection = new Connection(stream, options);
connection.host = host;
@@ -275,7 +302,7 @@
return connection;
};
-exports.createUDSConnection = function(path, options) {
+exports.createUDSConnection = function (path, options) {
var stream = net.createConnection(path);
var connection = new Connection(stream, options);
connection.path = path;
@@ -283,10 +310,11 @@
return connection;
};
-exports.createSSLConnection = function(host, port, options) {
- if (!('secureProtocol' in options) && !('secureOptions' in options)) {
+exports.createSSLConnection = function (host, port, options) {
+ if (!("secureProtocol" in options) && !("secureOptions" in options)) {
options.secureProtocol = "SSLv23_method";
- options.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3;
+ options.secureOptions =
+ constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3;
}
var stream = tls.connect(port, host, options);
@@ -297,15 +325,14 @@
return connection;
};
-
exports.createClient = createClient;
-var child_process = require('child_process');
-var StdIOConnection = exports.StdIOConnection = function(command, options) {
- var command_parts = command.split(' ');
+var child_process = require("child_process");
+var StdIOConnection = (exports.StdIOConnection = function (command, options) {
+ var command_parts = command.split(" ");
command = command_parts[0];
- var args = command_parts.splice(1,command_parts.length -1);
- var child = this.child = child_process.spawn(command,args);
+ var args = command_parts.splice(1, command_parts.length - 1);
+ var child = (this.child = child_process.spawn(command, args));
var self = this;
EventEmitter.call(this);
@@ -316,13 +343,13 @@
this.protocol = this.options.protocol || TBinaryProtocol;
this.offline_queue = [];
- if (log.getLogLevel() === 'debug') {
- this.child.stderr.on('data', function (err) {
- log.debug(err.toString(), 'CHILD ERROR');
+ if (log.getLogLevel() === "debug") {
+ this.child.stderr.on("data", function (err) {
+ log.debug(err.toString(), "CHILD ERROR");
});
- this.child.on('exit', function (code,signal) {
- log.debug(code + ':' + signal, 'CHILD EXITED');
+ this.child.on("exit", function (code, signal) {
+ log.debug(code + ":" + signal, "CHILD EXITED");
});
}
@@ -333,46 +360,47 @@
self.flush_offline_queue();
- this.connection.addListener("error", function(err) {
+ this.connection.addListener("error", function (err) {
self.emit("error", err);
});
// Add a close listener
- this.connection.addListener("close", function() {
+ this.connection.addListener("close", function () {
self.emit("close");
});
- child.stdout.addListener("data", self.transport.receiver(function(transport_with_data) {
- var message = new self.protocol(transport_with_data);
- try {
- var header = message.readMessageBegin();
- var dummy_seqid = header.rseqid * -1;
- var client = self.client;
- client._reqs[dummy_seqid] = function(err, success){
- transport_with_data.commitPosition();
+ child.stdout.addListener(
+ "data",
+ self.transport.receiver(function (transport_with_data) {
+ var message = new self.protocol(transport_with_data);
+ try {
+ var header = message.readMessageBegin();
+ var dummy_seqid = header.rseqid * -1;
+ var client = self.client;
+ client._reqs[dummy_seqid] = function (err, success) {
+ transport_with_data.commitPosition();
- var callback = client._reqs[header.rseqid];
- delete client._reqs[header.rseqid];
- if (callback) {
- callback(err, success);
+ var callback = client._reqs[header.rseqid];
+ delete client._reqs[header.rseqid];
+ if (callback) {
+ callback(err, success);
+ }
+ };
+ client["recv_" + header.fname](message, header.mtype, dummy_seqid);
+ } catch (e) {
+ if (e instanceof InputBufferUnderrunError) {
+ transport_with_data.rollbackPosition();
+ } else {
+ throw e;
}
- };
- client['recv_' + header.fname](message, header.mtype, dummy_seqid);
- }
- catch (e) {
- if (e instanceof InputBufferUnderrunError) {
- transport_with_data.rollbackPosition();
}
- else {
- throw e;
- }
- }
- }));
-};
+ }),
+ );
+});
util.inherits(StdIOConnection, EventEmitter);
-StdIOConnection.prototype.end = function() {
+StdIOConnection.prototype.end = function () {
this.connection.end();
};
@@ -383,12 +411,12 @@
// Reset offline queue
this.offline_queue = [];
// Attempt to write queued items
- offline_queue.forEach(function(data) {
+ offline_queue.forEach(function (data) {
self.write(data);
});
};
-StdIOConnection.prototype.write = function(data) {
+StdIOConnection.prototype.write = function (data) {
if (!this.connected) {
this.offline_queue.push(data);
return;
@@ -396,8 +424,8 @@
this.connection.write(data);
};
-exports.createStdIOConnection = function(command,options){
- return new StdIOConnection(command,options);
+exports.createStdIOConnection = function (command, options) {
+ return new StdIOConnection(command, options);
};
exports.createStdIOClient = createClient;
diff --git a/lib/nodejs/lib/thrift/create_client.js b/lib/nodejs/lib/thrift/create_client.js
index d6b77a8..b9021bd 100644
--- a/lib/nodejs/lib/thrift/create_client.js
+++ b/lib/nodejs/lib/thrift/create_client.js
@@ -43,7 +43,7 @@
// - Callback to call on flush
// Wrap the write method
- var writeCb = function(buf, seqid) {
+ var writeCb = function (buf, seqid) {
connection.write(buf, seqid);
};
var transport = new connection.transport(undefined, writeCb);
@@ -51,4 +51,4 @@
transport.client = client;
connection.client = client;
return client;
-};
+}
diff --git a/lib/nodejs/lib/thrift/framed_transport.js b/lib/nodejs/lib/thrift/framed_transport.js
index 058d230..7ede222 100644
--- a/lib/nodejs/lib/thrift/framed_transport.js
+++ b/lib/nodejs/lib/thrift/framed_transport.js
@@ -17,9 +17,9 @@
* under the License.
*/
-var binary = require('./binary');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
-var THeaderTransport = require('./header_transport');
+var binary = require("./binary");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
+var THeaderTransport = require("./header_transport");
module.exports = TFramedTransport;
@@ -30,14 +30,14 @@
this.outCount = 0;
this.readPos = 0;
this.onFlush = callback;
-};
+}
Object.setPrototypeOf(TFramedTransport.prototype, THeaderTransport.prototype);
-TFramedTransport.receiver = function(callback, seqid) {
+TFramedTransport.receiver = function (callback, seqid) {
var residual = new Buffer(0);
- return function(data) {
+ return function (data) {
residual = Buffer.concat([residual, Buffer.from(data)]);
while (residual.length > 0) {
@@ -61,34 +61,34 @@
};
};
-TFramedTransport.prototype.commitPosition = function(){},
-TFramedTransport.prototype.rollbackPosition = function(){},
-
+(TFramedTransport.prototype.commitPosition = function () {}),
+ (TFramedTransport.prototype.rollbackPosition = function () {}),
// TODO: Implement open/close support
-TFramedTransport.prototype.isOpen = function() {
- return true;
-};
-TFramedTransport.prototype.open = function() {};
-TFramedTransport.prototype.close = function() {};
+ (TFramedTransport.prototype.isOpen = function () {
+ return true;
+ });
+TFramedTransport.prototype.open = function () {};
+TFramedTransport.prototype.close = function () {};
- // Set the seqid of the message in the client
- // So that callbacks can be found
-TFramedTransport.prototype.setCurrSeqId = function(seqid) {
+// Set the seqid of the message in the client
+// So that callbacks can be found
+TFramedTransport.prototype.setCurrSeqId = function (seqid) {
this._seqid = seqid;
};
-TFramedTransport.prototype.ensureAvailable = function(len) {
+TFramedTransport.prototype.ensureAvailable = function (len) {
if (this.readPos + len > this.inBuf.length) {
throw new InputBufferUnderrunError();
}
};
-TFramedTransport.prototype.read = function(len) { // this function will be used for each frames.
+TFramedTransport.prototype.read = function (len) {
+ // this function will be used for each frames.
this.ensureAvailable(len);
var end = this.readPos + len;
if (this.inBuf.length < end) {
- throw new Error('read(' + len + ') failed - not enough data');
+ throw new Error("read(" + len + ") failed - not enough data");
}
var buf = this.inBuf.slice(this.readPos, end);
@@ -96,68 +96,68 @@
return buf;
};
-TFramedTransport.prototype.readByte = function() {
+TFramedTransport.prototype.readByte = function () {
this.ensureAvailable(1);
return binary.readByte(this.inBuf[this.readPos++]);
};
-TFramedTransport.prototype.readI16 = function() {
+TFramedTransport.prototype.readI16 = function () {
this.ensureAvailable(2);
var i16 = binary.readI16(this.inBuf, this.readPos);
this.readPos += 2;
return i16;
};
-TFramedTransport.prototype.readI32 = function() {
+TFramedTransport.prototype.readI32 = function () {
this.ensureAvailable(4);
var i32 = binary.readI32(this.inBuf, this.readPos);
this.readPos += 4;
return i32;
};
-TFramedTransport.prototype.readDouble = function() {
+TFramedTransport.prototype.readDouble = function () {
this.ensureAvailable(8);
var d = binary.readDouble(this.inBuf, this.readPos);
this.readPos += 8;
return d;
};
-TFramedTransport.prototype.readString = function(len) {
+TFramedTransport.prototype.readString = function (len) {
this.ensureAvailable(len);
- var str = this.inBuf.toString('utf8', this.readPos, this.readPos + len);
+ var str = this.inBuf.toString("utf8", this.readPos, this.readPos + len);
this.readPos += len;
return str;
};
-TFramedTransport.prototype.borrow = function() {
+TFramedTransport.prototype.borrow = function () {
return {
buf: this.inBuf,
readIndex: this.readPos,
- writeIndex: this.inBuf.length
+ writeIndex: this.inBuf.length,
};
};
-TFramedTransport.prototype.consume = function(bytesConsumed) {
+TFramedTransport.prototype.consume = function (bytesConsumed) {
this.readPos += bytesConsumed;
};
-TFramedTransport.prototype.write = function(buf, encoding) {
- if (typeof(buf) === "string") {
- buf = new Buffer(buf, encoding || 'utf8');
+TFramedTransport.prototype.write = function (buf, encoding) {
+ if (typeof buf === "string") {
+ buf = new Buffer(buf, encoding || "utf8");
}
this.outBuffers.push(buf);
this.outCount += buf.length;
};
-TFramedTransport.prototype.flush = function() {
+TFramedTransport.prototype.flush = function () {
// If the seqid of the callback is available pass it to the onFlush
// Then remove the current seqid
var seqid = this._seqid;
this._seqid = null;
var out = new Buffer(this.outCount),
- pos = 0;
- this.outBuffers.forEach(function(buf) {
+ pos = 0;
+ this.outBuffers.forEach(function (buf) {
buf.copy(out, pos, 0);
pos += buf.length;
});
diff --git a/lib/nodejs/lib/thrift/header_protocol.js b/lib/nodejs/lib/thrift/header_protocol.js
index 8971751..2a48a4d 100644
--- a/lib/nodejs/lib/thrift/header_protocol.js
+++ b/lib/nodejs/lib/thrift/header_protocol.js
@@ -16,10 +16,10 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var TBinaryProtocol = require('./binary_protocol');
-var TCompactProtocol = require('./compact_protocol');
-var THeaderTransport = require('./header_transport');
+var util = require("util");
+var TBinaryProtocol = require("./binary_protocol");
+var TCompactProtocol = require("./compact_protocol");
+var THeaderTransport = require("./header_transport");
var ProtocolMap = {};
ProtocolMap[THeaderTransport.SubprotocolId.BINARY] = TBinaryProtocol;
@@ -54,204 +54,206 @@
function THeaderProtocol(trans) {
if (!(trans instanceof THeaderTransport)) {
throw new THeaderProtocolError(
- 'Only transports that inherit THeaderTransport can be' +
- ' used with THeaderProtocol'
+ "Only transports that inherit THeaderTransport can be" +
+ " used with THeaderProtocol",
);
}
this.trans = trans;
this.setProtocol();
-};
+}
-THeaderProtocol.prototype.flush = function() {
- // Headers must be written prior to flushing because because
- // you need to calculate the length of the payload for the length
- // field of the header
+THeaderProtocol.prototype.flush = function () {
+ // Headers must be written prior to flushing because because
+ // you need to calculate the length of the payload for the length
+ // field of the header
this.trans.writeHeaders();
return this.trans.flush();
};
-THeaderProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
+THeaderProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
return this.protocol.writeMessageBegin(name, type, seqid);
};
-THeaderProtocol.prototype.writeMessageEnd = function() {
+THeaderProtocol.prototype.writeMessageEnd = function () {
return this.protocol.writeMessageEnd();
};
-THeaderProtocol.prototype.writeStructBegin = function(name) {
+THeaderProtocol.prototype.writeStructBegin = function (name) {
return this.protocol.writeStructBegin(name);
};
-THeaderProtocol.prototype.writeStructEnd = function() {
+THeaderProtocol.prototype.writeStructEnd = function () {
return this.protocol.writeStructEnd();
};
-THeaderProtocol.prototype.writeFieldBegin = function(name, type, id) {
+THeaderProtocol.prototype.writeFieldBegin = function (name, type, id) {
return this.protocol.writeFieldBegin(name, type, id);
-}
+};
-THeaderProtocol.prototype.writeFieldEnd = function() {
+THeaderProtocol.prototype.writeFieldEnd = function () {
return this.protocol.writeFieldEnd();
};
-THeaderProtocol.prototype.writeFieldStop = function() {
+THeaderProtocol.prototype.writeFieldStop = function () {
return this.protocol.writeFieldStop();
};
-THeaderProtocol.prototype.writeMapBegin = function(ktype, vtype, size) {
+THeaderProtocol.prototype.writeMapBegin = function (ktype, vtype, size) {
return this.protocol.writeMapBegin(ktype, vtype, size);
};
-THeaderProtocol.prototype.writeMapEnd = function() {
+THeaderProtocol.prototype.writeMapEnd = function () {
return this.protocol.writeMapEnd();
};
-THeaderProtocol.prototype.writeListBegin = function(etype, size) {
+THeaderProtocol.prototype.writeListBegin = function (etype, size) {
return this.protocol.writeListBegin(etype, size);
};
-THeaderProtocol.prototype.writeListEnd = function() {
+THeaderProtocol.prototype.writeListEnd = function () {
return this.protocol.writeListEnd();
};
-THeaderProtocol.prototype.writeSetBegin = function(etype, size) {
+THeaderProtocol.prototype.writeSetBegin = function (etype, size) {
return this.protocol.writeSetBegin(etype, size);
};
-THeaderProtocol.prototype.writeSetEnd = function() {
+THeaderProtocol.prototype.writeSetEnd = function () {
return this.protocol.writeSetEnd();
};
-THeaderProtocol.prototype.writeBool = function(b) {
+THeaderProtocol.prototype.writeBool = function (b) {
return this.protocol.writeBool(b);
};
-THeaderProtocol.prototype.writeByte = function(b) {
+THeaderProtocol.prototype.writeByte = function (b) {
return this.protocol.writeByte(b);
};
-THeaderProtocol.prototype.writeI16 = function(i16) {
+THeaderProtocol.prototype.writeI16 = function (i16) {
return this.protocol.writeI16(i16);
};
-THeaderProtocol.prototype.writeI32 = function(i32) {
+THeaderProtocol.prototype.writeI32 = function (i32) {
return this.protocol.writeI32(i32);
};
-THeaderProtocol.prototype.writeI64 = function(i64) {
+THeaderProtocol.prototype.writeI64 = function (i64) {
return this.protocol.writeI64(i64);
};
-THeaderProtocol.prototype.writeDouble = function(dub) {
+THeaderProtocol.prototype.writeDouble = function (dub) {
return this.protocol.writeDouble(dub);
};
-THeaderProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) {
+THeaderProtocol.prototype.writeStringOrBinary = function (name, encoding, arg) {
return this.protocol.writeStringOrBinary(name, encoding, arg);
};
-THeaderProtocol.prototype.writeString = function(arg) {
+THeaderProtocol.prototype.writeString = function (arg) {
return this.protocol.writeString(arg);
};
-THeaderProtocol.prototype.writeBinary = function(arg) {
+THeaderProtocol.prototype.writeBinary = function (arg) {
return this.protocol.writeBinary(arg);
};
-THeaderProtocol.prototype.readMessageBegin = function() {
+THeaderProtocol.prototype.readMessageBegin = function () {
this.trans.readHeaders();
this.setProtocol();
return this.protocol.readMessageBegin();
};
-THeaderProtocol.prototype.readMessageEnd = function() {
+THeaderProtocol.prototype.readMessageEnd = function () {
return this.protocol.readMessageEnd();
};
-THeaderProtocol.prototype.readStructBegin = function() {
+THeaderProtocol.prototype.readStructBegin = function () {
return this.protocol.readStructBegin();
};
-THeaderProtocol.prototype.readStructEnd = function() {
+THeaderProtocol.prototype.readStructEnd = function () {
return this.protocol.readStructEnd();
};
-THeaderProtocol.prototype.readFieldBegin = function() {
+THeaderProtocol.prototype.readFieldBegin = function () {
return this.protocol.readFieldBegin();
};
-THeaderProtocol.prototype.readFieldEnd = function() {
+THeaderProtocol.prototype.readFieldEnd = function () {
return this.protocol.readFieldEnd();
};
-THeaderProtocol.prototype.readMapBegin = function() {
+THeaderProtocol.prototype.readMapBegin = function () {
return this.protocol.readMapBegin();
};
-THeaderProtocol.prototype.readMapEnd = function() {
+THeaderProtocol.prototype.readMapEnd = function () {
return this.protocol.readMapEnd();
};
-THeaderProtocol.prototype.readListBegin = function() {
+THeaderProtocol.prototype.readListBegin = function () {
return this.protocol.readListBegin();
};
-THeaderProtocol.prototype.readListEnd = function() {
+THeaderProtocol.prototype.readListEnd = function () {
return this.protocol.readListEnd();
};
-THeaderProtocol.prototype.readSetBegin = function() {
+THeaderProtocol.prototype.readSetBegin = function () {
return this.protocol.readSetBegin();
};
-THeaderProtocol.prototype.readSetEnd = function() {
+THeaderProtocol.prototype.readSetEnd = function () {
return this.protocol.readSetEnd();
};
-THeaderProtocol.prototype.readBool = function() {
+THeaderProtocol.prototype.readBool = function () {
return this.protocol.readBool();
};
-THeaderProtocol.prototype.readByte = function() {
+THeaderProtocol.prototype.readByte = function () {
return this.protocol.readByte();
};
-THeaderProtocol.prototype.readI16 = function() {
+THeaderProtocol.prototype.readI16 = function () {
return this.protocol.readI16();
};
-THeaderProtocol.prototype.readI32 = function() {
+THeaderProtocol.prototype.readI32 = function () {
return this.protocol.readI32();
};
-THeaderProtocol.prototype.readI64 = function() {
+THeaderProtocol.prototype.readI64 = function () {
return this.protocol.readI64();
};
-THeaderProtocol.prototype.readDouble = function() {
+THeaderProtocol.prototype.readDouble = function () {
return this.protocol.readDouble();
};
-THeaderProtocol.prototype.readBinary = function() {
+THeaderProtocol.prototype.readBinary = function () {
return this.protocol.readBinary();
};
-THeaderProtocol.prototype.readString = function() {
+THeaderProtocol.prototype.readString = function () {
return this.protocol.readString();
};
-THeaderProtocol.prototype.getTransport = function() {
+THeaderProtocol.prototype.getTransport = function () {
return this.trans;
};
-THeaderProtocol.prototype.skip = function(type) {
+THeaderProtocol.prototype.skip = function (type) {
return this.protocol.skip(type);
};
-THeaderProtocol.prototype.setProtocol = function(subProtocolId) {
+THeaderProtocol.prototype.setProtocol = function (subProtocolId) {
var subProtocolId = this.trans.getProtocolId();
if (!ProtocolMap[subProtocolId]) {
- throw new THeaderProtocolError('Headers not supported for protocol ' + subProtocolId);
+ throw new THeaderProtocolError(
+ "Headers not supported for protocol " + subProtocolId,
+ );
}
this.protocol = new ProtocolMap[subProtocolId](this.trans);
diff --git a/lib/nodejs/lib/thrift/header_transport.js b/lib/nodejs/lib/thrift/header_transport.js
index ec8624b..37da492 100644
--- a/lib/nodejs/lib/thrift/header_transport.js
+++ b/lib/nodejs/lib/thrift/header_transport.js
@@ -17,10 +17,10 @@
* under the License.
*/
-var util = require('util');
-var TCompactProtocol = require('./compact_protocol');
-var TBinaryProtocol = require('./binary_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var util = require("util");
+var TCompactProtocol = require("./compact_protocol");
+var TBinaryProtocol = require("./binary_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
function THeaderTransportError(message) {
Error.call(this);
@@ -45,51 +45,51 @@
var HEADER_SIZE_OFFSET = 96 / 8;
var HEADER_START_OFFSET = 112 / 8;
-var HEADER_MAGIC = 0x0FFF;
+var HEADER_MAGIC = 0x0fff;
var TINFO_HEADER_KEY_VALUE_TYPE = 0x01;
-var MAX_FRAME_SIZE = 0x3FFFFFFF;
+var MAX_FRAME_SIZE = 0x3fffffff;
- // A helper class for reading/writing varints. Uses
- // TCompactProtocol under the hood
+// A helper class for reading/writing varints. Uses
+// TCompactProtocol under the hood
function VarintHelper(readBuffer) {
- var TBufferedTransport = require('./buffered_transport');
+ var TBufferedTransport = require("./buffered_transport");
this.outputBuffer = null;
var _this = this;
- this.transport = new TBufferedTransport(null, function(output) {
+ this.transport = new TBufferedTransport(null, function (output) {
_this.outputBuffer = output;
});
this.transport.inBuf = readBuffer || Buffer.alloc(0);
this.transport.writeCursor = this.transport.inBuf.length;
this.protocol = new TCompactProtocol(this.transport);
-};
+}
-VarintHelper.prototype.readVarint32 = function() {
+VarintHelper.prototype.readVarint32 = function () {
return this.protocol.readVarint32();
};
-VarintHelper.prototype.writeVarint32 = function(i) {
+VarintHelper.prototype.writeVarint32 = function (i) {
this.protocol.writeVarint32(i);
};
-VarintHelper.prototype.readString = function() {
+VarintHelper.prototype.readString = function () {
return this.protocol.readString();
};
-VarintHelper.prototype.writeString = function(str) {
+VarintHelper.prototype.writeString = function (str) {
this.protocol.writeString(str);
-}
+};
-VarintHelper.prototype.getOutCount = function() {
+VarintHelper.prototype.getOutCount = function () {
return this.transport.outCount;
};
-VarintHelper.prototype.write = function(str) {
+VarintHelper.prototype.write = function (str) {
this.transport.write(str);
};
-VarintHelper.prototype.toBuffer = function() {
+VarintHelper.prototype.toBuffer = function () {
this.transport.flush();
return this.outputBuffer;
};
@@ -127,87 +127,90 @@
this.flags = null;
this.seqid = 0;
this.shouldWriteHeaders = true;
-};
+}
-var validateHeaders = function(key, value) {
- if (typeof key !== 'string' || typeof value !== 'string') {
- throw new THeaderTransportError('Header key and values must be strings');
+var validateHeaders = function (key, value) {
+ if (typeof key !== "string" || typeof value !== "string") {
+ throw new THeaderTransportError("Header key and values must be strings");
}
};
-var validateProtocolId = function(protocolId) {
+var validateProtocolId = function (protocolId) {
var protocols = Object.keys(THeaderTransport.SubprotocolId);
for (var i = 0; i < protocols.length; i++) {
- if (protocolId === THeaderTransport.SubprotocolId[protocols[i]]) return true;
+ if (protocolId === THeaderTransport.SubprotocolId[protocols[i]])
+ return true;
}
- throw new Error(protocolId + ' is not a valid protocol id');
+ throw new Error(protocolId + " is not a valid protocol id");
};
-THeaderTransport.prototype.setSeqId = function(seqid) {
+THeaderTransport.prototype.setSeqId = function (seqid) {
this.seqid = seqid;
};
-THeaderTransport.prototype.getSeqId = function(seqid) {
+THeaderTransport.prototype.getSeqId = function (seqid) {
return this.seqid;
};
-THeaderTransport.prototype.setFlags = function(flags) {
+THeaderTransport.prototype.setFlags = function (flags) {
this.flags = flags;
};
-THeaderTransport.prototype.getReadHeaders = function() {
+THeaderTransport.prototype.getReadHeaders = function () {
return this.rheaders;
};
-THeaderTransport.prototype.setReadHeader = function(key, value) {
+THeaderTransport.prototype.setReadHeader = function (key, value) {
validateHeaders(key, value);
this.rheaders[key] = value;
};
-THeaderTransport.prototype.clearReadHeaders = function() {
+THeaderTransport.prototype.clearReadHeaders = function () {
this.rheaders = {};
};
-THeaderTransport.prototype.getWriteHeaders = function() {
+THeaderTransport.prototype.getWriteHeaders = function () {
return this.wheaders;
};
-THeaderTransport.prototype.setWriteHeader = function(key, value) {
+THeaderTransport.prototype.setWriteHeader = function (key, value) {
validateHeaders(key, value);
this.wheaders[key] = value;
};
-THeaderTransport.prototype.clearWriteHeaders = function() {
+THeaderTransport.prototype.clearWriteHeaders = function () {
this.wheaders = {};
};
-THeaderTransport.prototype.setMaxFrameSize = function(frameSize) {
+THeaderTransport.prototype.setMaxFrameSize = function (frameSize) {
this.maxFrameSize = frameSize;
};
-THeaderTransport.prototype.setProtocolId = function(protocolId) {
+THeaderTransport.prototype.setProtocolId = function (protocolId) {
validateProtocolId(protocolId);
this.protocolId = protocolId;
};
-THeaderTransport.prototype.getProtocolId = function() {
+THeaderTransport.prototype.getProtocolId = function () {
return this.protocolId;
};
-var isUnframedBinary = function(readBuffer) {
+var isUnframedBinary = function (readBuffer) {
var version = readBuffer.readInt32BE();
return (version & TBinaryProtocol.VERSION_MASK) === TBinaryProtocol.VERSION_1;
-}
+};
-var isUnframedCompact = function(readBuffer) {
+var isUnframedCompact = function (readBuffer) {
var protocolId = readBuffer.readInt8(COMPACT_PROTOCOL_OFFSET);
var version = readBuffer.readInt8(COMPACT_PROTOCOL_VERSION_OFFSET);
- return protocolId === TCompactProtocol.PROTOCOL_ID &&
- (version & TCompactProtocol.VERSION_MASK) === TCompactProtocol.VERSION_N;
-}
+ return (
+ protocolId === TCompactProtocol.PROTOCOL_ID &&
+ (version & TCompactProtocol.VERSION_MASK) === TCompactProtocol.VERSION_N
+ );
+};
-THeaderTransport.prototype.readHeaders = function() {
+THeaderTransport.prototype.readHeaders = function () {
var readBuffer = this.inBuf;
var isUnframed = false;
@@ -228,7 +231,7 @@
var frameSize = readBuffer.readInt32BE(FRAME_SIZE_OFFSET);
if (frameSize > this.maxFrameSize) {
- throw new THeaderTransportError('Frame exceeds maximum frame size');
+ throw new THeaderTransportError("Frame exceeds maximum frame size");
}
var headerMagic = readBuffer.readInt16BE(HEADER_MAGIC_OFFSET);
@@ -242,7 +245,7 @@
var headerSize = readBuffer.readInt16BE(HEADER_SIZE_OFFSET) * 4;
var endOfHeaders = HEADER_START_OFFSET + headerSize;
if (endOfHeaders > readBuffer.length) {
- throw new THeaderTransportError('Header size is greater than frame size');
+ throw new THeaderTransportError("Header size is greater than frame size");
}
var headerBuffer = Buffer.alloc(headerSize);
@@ -252,7 +255,7 @@
this.setProtocolId(varintHelper.readVarint32());
var transformCount = varintHelper.readVarint32();
if (transformCount > 0) {
- throw new THeaderTransportError('Transforms are not yet supported');
+ throw new THeaderTransportError("Transforms are not yet supported");
}
while (true) {
@@ -281,7 +284,7 @@
return this.getReadHeaders();
};
-THeaderTransport.prototype.writeHeaders = function() {
+THeaderTransport.prototype.writeHeaders = function () {
// only write headers on the server if the client contained headers
if (!this.shouldWriteHeaders) {
return;
@@ -305,11 +308,13 @@
varintWriter.writeString(value);
}
}
- var headerSizeWithoutPadding = varintWriter.getOutCount();
+ var headerSizeWithoutPadding = varintWriter.getOutCount();
var paddingNeeded = (4 - (headerSizeWithoutPadding % 4)) % 4;
var headerSize = Buffer.alloc(2);
- headerSize.writeInt16BE(Math.floor((headerSizeWithoutPadding + paddingNeeded) / 4));
+ headerSize.writeInt16BE(
+ Math.floor((headerSizeWithoutPadding + paddingNeeded) / 4),
+ );
var paddingBuffer = Buffer.alloc(paddingNeeded);
paddingBuffer.fill(0x00);
diff --git a/lib/nodejs/lib/thrift/http_connection.js b/lib/nodejs/lib/thrift/http_connection.js
index 17e0d0c..50d3312 100644
--- a/lib/nodejs/lib/thrift/http_connection.js
+++ b/lib/nodejs/lib/thrift/http_connection.js
@@ -16,17 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var http = require('http');
-var https = require('https');
-var EventEmitter = require('events').EventEmitter;
-var thrift = require('./thrift');
+var util = require("util");
+var http = require("http");
+var https = require("https");
+var EventEmitter = require("events").EventEmitter;
+var thrift = require("./thrift");
-var TBufferedTransport = require('./buffered_transport');
-var TBinaryProtocol = require('./binary_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TBinaryProtocol = require("./binary_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
-var createClient = require('./create_client');
+var createClient = require("./create_client");
/**
* @class
@@ -69,7 +69,7 @@
* semantics implemented over the Node.js http.request() method.
* @see {@link createHttpConnection}
*/
-var HttpConnection = exports.HttpConnection = function(options) {
+var HttpConnection = (exports.HttpConnection = function (options) {
//Initialize the emitter base object
EventEmitter.call(this);
@@ -88,17 +88,17 @@
host: this.host,
port: this.port,
socketPath: this.socketPath,
- path: this.options.path || '/',
- method: 'POST',
+ path: this.options.path || "/",
+ method: "POST",
headers: this.options.headers || {},
- responseType: this.options.responseType || null
+ responseType: this.options.responseType || null,
};
for (var attrname in this.options.nodeOptions) {
this.nodeOptions[attrname] = this.options.nodeOptions[attrname];
}
/*jshint -W069 */
- if (! this.nodeOptions.headers['Connection']) {
- this.nodeOptions.headers['Connection'] = 'keep-alive';
+ if (!this.nodeOptions.headers["Connection"]) {
+ this.nodeOptions.headers["Connection"] = "keep-alive";
}
/*jshint +W069 */
@@ -131,41 +131,42 @@
delete self.seqId2Service[header.rseqid];
}
/*jshint -W083 */
- client._reqs[dummy_seqid] = function(err, success){
+ client._reqs[dummy_seqid] = function (err, success) {
transport_with_data.commitPosition();
var clientCallback = client._reqs[header.rseqid];
delete client._reqs[header.rseqid];
if (clientCallback) {
- process.nextTick(function() {
+ process.nextTick(function () {
clientCallback(err, success);
});
}
};
/*jshint +W083 */
- if(client['recv_' + header.fname]) {
- client['recv_' + header.fname](proto, header.mtype, dummy_seqid);
+ if (client["recv_" + header.fname]) {
+ client["recv_" + header.fname](proto, header.mtype, dummy_seqid);
} else {
delete client._reqs[dummy_seqid];
- self.emit("error",
- new thrift.TApplicationException(
- thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
- "Received a response to an unknown RPC function"));
+ self.emit(
+ "error",
+ new thrift.TApplicationException(
+ thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
+ "Received a response to an unknown RPC function",
+ ),
+ );
}
}
- }
- catch (e) {
+ } catch (e) {
if (e instanceof InputBufferUnderrunError) {
transport_with_data.rollbackPosition();
} else {
- self.emit('error', e);
+ self.emit("error", e);
}
}
}
-
//Response handler
//////////////////////////////////////////////////
- this.responseCallback = function(response) {
+ this.responseCallback = function (response) {
var data = [];
var dataLen = 0;
@@ -173,16 +174,18 @@
this.emit("error", new THTTPException(response));
}
- response.on('error', function (e) {
+ response.on("error", function (e) {
self.emit("error", e);
});
// When running directly under node, chunk will be a buffer,
// however, when running in a Browser (e.g. Browserify), chunk
// will be a string or an ArrayBuffer.
- response.on('data', function (chunk) {
- if ((typeof chunk == 'string') ||
- (Object.prototype.toString.call(chunk) == '[object Uint8Array]')) {
+ response.on("data", function (chunk) {
+ if (
+ typeof chunk == "string" ||
+ Object.prototype.toString.call(chunk) == "[object Uint8Array]"
+ ) {
// Wrap ArrayBuffer/string in a Buffer so data[i].copy will work
data.push(new Buffer(chunk));
} else {
@@ -191,9 +194,9 @@
dataLen += chunk.length;
});
- response.on('end', function(){
+ response.on("end", function () {
var buf = new Buffer(dataLen);
- for (var i=0, len=data.length, pos=0; i<len; i++) {
+ for (var i = 0, len = data.length, pos = 0; i < len; i++) {
data[i].copy(buf, pos);
pos += data[i].length;
}
@@ -202,7 +205,7 @@
self.transport.receiver(decodeCallback)(buf);
});
};
-};
+});
util.inherits(HttpConnection, EventEmitter);
/**
@@ -212,16 +215,16 @@
* @event {error} the "error" event is raised upon request failure passing the
* Node.js error object to the listener.
*/
-HttpConnection.prototype.write = function(data) {
+HttpConnection.prototype.write = function (data) {
var self = this;
var opts = self.nodeOptions;
opts.headers["Content-length"] = data.length;
if (!opts.headers["Content-Type"])
opts.headers["Content-Type"] = "application/x-thrift";
- var req = (self.https) ?
- https.request(opts, self.responseCallback) :
- http.request(opts, self.responseCallback);
- req.on('error', function(err) {
+ var req = self.https
+ ? https.request(opts, self.responseCallback)
+ : http.request(opts, self.responseCallback);
+ req.on("error", function (err) {
self.emit("error", err);
});
req.write(data);
@@ -237,19 +240,18 @@
* @returns {HttpConnection} The connection object.
* @see {@link ConnectOptions}
*/
-exports.createHttpConnection = function(host, port, options) {
+exports.createHttpConnection = function (host, port, options) {
options.host = host;
options.port = port || 80;
return new HttpConnection(options);
};
-exports.createHttpUDSConnection = function(path, options) {
+exports.createHttpUDSConnection = function (path, options) {
options.socketPath = path;
return new HttpConnection(options);
};
-exports.createHttpClient = createClient
-
+exports.createHttpClient = createClient;
function THTTPException(response) {
thrift.TApplicationException.call(this);
@@ -261,6 +263,7 @@
this.statusCode = response.statusCode;
this.response = response;
this.type = thrift.TApplicationExceptionType.PROTOCOL_ERROR;
- this.message = "Received a response with a bad HTTP status code: " + response.statusCode;
+ this.message =
+ "Received a response with a bad HTTP status code: " + response.statusCode;
}
util.inherits(THTTPException, thrift.TApplicationException);
diff --git a/lib/nodejs/lib/thrift/index.js b/lib/nodejs/lib/thrift/index.js
index df4a5dc..5f0010f 100644
--- a/lib/nodejs/lib/thrift/index.js
+++ b/lib/nodejs/lib/thrift/index.js
@@ -16,14 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
-exports.Thrift = require('./thrift');
+exports.Thrift = require("./thrift");
-var log = require('./log');
+var log = require("./log");
exports.setLogFunc = log.setLogFunc;
exports.setLogLevel = log.setLogLevel;
exports.getLogLevel = log.getLogLevel;
-var connection = require('./connection');
+var connection = require("./connection");
exports.Connection = connection.Connection;
exports.createClient = connection.createClient;
exports.createConnection = connection.createConnection;
@@ -32,34 +32,34 @@
exports.createStdIOClient = connection.createStdIOClient;
exports.createStdIOConnection = connection.createStdIOConnection;
-var httpConnection = require('./http_connection');
+var httpConnection = require("./http_connection");
exports.HttpConnection = httpConnection.HttpConnection;
exports.createHttpConnection = httpConnection.createHttpConnection;
exports.createHttpUDSConnection = httpConnection.createHttpUDSConnection;
exports.createHttpClient = httpConnection.createHttpClient;
-var wsConnection = require('./ws_connection');
+var wsConnection = require("./ws_connection");
exports.WSConnection = wsConnection.WSConnection;
exports.createWSConnection = wsConnection.createWSConnection;
exports.createWSClient = wsConnection.createWSClient;
-var xhrConnection = require('./xhr_connection');
+var xhrConnection = require("./xhr_connection");
exports.XHRConnection = xhrConnection.XHRConnection;
exports.createXHRConnection = xhrConnection.createXHRConnection;
exports.createXHRClient = xhrConnection.createXHRClient;
-var server = require('./server');
+var server = require("./server");
exports.createServer = server.createServer;
exports.createMultiplexServer = server.createMultiplexServer;
-var web_server = require('./web_server');
+var web_server = require("./web_server");
exports.createWebServer = web_server.createWebServer;
-exports.Int64 = require('node-int64');
-exports.Q = require('q');
+exports.Int64 = require("node-int64");
+exports.Q = require("q");
-var mpxProcessor = require('./multiplexed_processor');
-var mpxProtocol = require('./multiplexed_protocol');
+var mpxProcessor = require("./multiplexed_processor");
+var mpxProtocol = require("./multiplexed_protocol");
exports.MultiplexedProcessor = mpxProcessor.MultiplexedProcessor;
exports.Multiplexer = mpxProtocol.Multiplexer;
@@ -67,12 +67,12 @@
* Export transport and protocol so they can be used outside of a
* cassandra/server context
*/
-exports.TBufferedTransport = require('./buffered_transport');
-exports.TFramedTransport = require('./framed_transport');
+exports.TBufferedTransport = require("./buffered_transport");
+exports.TFramedTransport = require("./framed_transport");
-exports.TJSONProtocol = require('./json_protocol');
-exports.TBinaryProtocol = require('./binary_protocol');
-exports.TCompactProtocol = require('./compact_protocol');
-exports.THeaderProtocol = require('./header_protocol');
+exports.TJSONProtocol = require("./json_protocol");
+exports.TBinaryProtocol = require("./binary_protocol");
+exports.TCompactProtocol = require("./compact_protocol");
+exports.THeaderProtocol = require("./header_protocol");
-exports.InputBufferUnderrunError = require('./input_buffer_underrun_error');
+exports.InputBufferUnderrunError = require("./input_buffer_underrun_error");
diff --git a/lib/nodejs/lib/thrift/input_buffer_underrun_error.js b/lib/nodejs/lib/thrift/input_buffer_underrun_error.js
index e424540..9542854 100644
--- a/lib/nodejs/lib/thrift/input_buffer_underrun_error.js
+++ b/lib/nodejs/lib/thrift/input_buffer_underrun_error.js
@@ -27,6 +27,6 @@
}
this.name = this.constructor.name;
this.message = message;
-};
+}
util.inherits(InputBufferUnderrunError, Error);
diff --git a/lib/nodejs/lib/thrift/int64_util.js b/lib/nodejs/lib/thrift/int64_util.js
index e8d707d..84588c5 100644
--- a/lib/nodejs/lib/thrift/int64_util.js
+++ b/lib/nodejs/lib/thrift/int64_util.js
@@ -17,20 +17,19 @@
* under the License.
*/
-var Int64 = require('node-int64');
+var Int64 = require("node-int64");
-var Int64Util = module.exports = {};
+var Int64Util = (module.exports = {});
var POW2_24 = Math.pow(2, 24);
var POW2_31 = Math.pow(2, 31);
var POW2_32 = Math.pow(2, 32);
var POW10_11 = Math.pow(10, 11);
-Int64Util.toDecimalString = function(i64) {
+Int64Util.toDecimalString = function (i64) {
var b = i64.buffer;
var o = i64.offset;
- if ((!b[o] && !(b[o + 1] & 0xe0)) ||
- (!~b[o] && !~(b[o + 1] & 0xe0))) {
+ if ((!b[o] && !(b[o + 1] & 0xe0)) || (!~b[o] && !~(b[o + 1] & 0xe0))) {
// The magnitude is small enough.
return i64.toString();
} else {
@@ -47,34 +46,39 @@
}
var high2 = b[o + 1] + (b[o] << 8);
// Lesser 11 digits with exceeding values but is under 53 bits capacity.
- var low = b[o + 7] + (b[o + 6] << 8) + (b[o + 5] << 16)
- + b[o + 4] * POW2_24 // Bit shift renders 32th bit as sign, so use multiplication
- + (b[o + 3] + (b[o + 2] << 8)) * POW2_32 + high2 * 74976710656; // The literal is 2^48 % 10^11
+ var low =
+ b[o + 7] +
+ (b[o + 6] << 8) +
+ (b[o + 5] << 16) +
+ b[o + 4] * POW2_24 + // Bit shift renders 32th bit as sign, so use multiplication
+ (b[o + 3] + (b[o + 2] << 8)) * POW2_32 +
+ high2 * 74976710656; // The literal is 2^48 % 10^11
// 12th digit and greater.
- var high = Math.floor(low / POW10_11) + high2 * 2814; // The literal is 2^48 / 10^11
+ var high = Math.floor(low / POW10_11) + high2 * 2814; // The literal is 2^48 / 10^11
// Make it exactly 11 with leading zeros.
- low = ('00000000000' + String(low % POW10_11)).slice(-11);
- return (negative ? '-' : '') + String(high) + low;
+ low = ("00000000000" + String(low % POW10_11)).slice(-11);
+ return (negative ? "-" : "") + String(high) + low;
}
};
-Int64Util.fromDecimalString = function(text) {
- var negative = text.charAt(0) === '-';
+Int64Util.fromDecimalString = function (text) {
+ var negative = text.charAt(0) === "-";
if (text.length < (negative ? 17 : 16)) {
// The magnitude is smaller than 2^53.
return new Int64(+text);
} else if (text.length > (negative ? 20 : 19)) {
- throw new RangeError('Too many digits for Int64: ' + text);
+ throw new RangeError("Too many digits for Int64: " + text);
} else {
// Most significant (up to 5) digits
var high5 = +text.slice(negative ? 1 : 0, -15);
- var low = +text.slice(-15) + high5 * 2764472320; // The literal is 10^15 % 2^32
- var high = Math.floor(low / POW2_32) + high5 * 232830; // The literal is 10^15 / 2^&32
+ var low = +text.slice(-15) + high5 * 2764472320; // The literal is 10^15 % 2^32
+ var high = Math.floor(low / POW2_32) + high5 * 232830; // The literal is 10^15 / 2^&32
low = low % POW2_32;
- if (high >= POW2_31 &&
- !(negative && high == POW2_31 && low == 0) // Allow minimum Int64
- ) {
- throw new RangeError('The magnitude is too large for Int64.');
+ if (
+ high >= POW2_31 &&
+ !(negative && high == POW2_31 && low == 0) // Allow minimum Int64
+ ) {
+ throw new RangeError("The magnitude is too large for Int64.");
}
if (negative) {
// 2's complement
diff --git a/lib/nodejs/lib/thrift/json_parse.js b/lib/nodejs/lib/thrift/json_parse.js
index 93b0bf2..3d111c0 100644
--- a/lib/nodejs/lib/thrift/json_parse.js
+++ b/lib/nodejs/lib/thrift/json_parse.js
@@ -12,7 +12,6 @@
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
-
/*jslint for */
/*property
@@ -20,280 +19,260 @@
prototype, push, r, t, text
*/
-var Int64 = require('node-int64');
-var Int64Util = require('./int64_util');
+var Int64 = require("node-int64");
+var Int64Util = require("./int64_util");
-var json_parse = module.exports = (function () {
- "use strict";
+var json_parse = (module.exports = (function () {
+ "use strict";
-// This is a function that can parse a JSON text, producing a JavaScript
-// data structure. It is a simple, recursive descent parser. It does not use
-// eval or regular expressions, so it can be used as a model for implementing
-// a JSON parser in other languages.
+ // This is a function that can parse a JSON text, producing a JavaScript
+ // data structure. It is a simple, recursive descent parser. It does not use
+ // eval or regular expressions, so it can be used as a model for implementing
+ // a JSON parser in other languages.
-// We are defining the function inside of another function to avoid creating
-// global variables.
+ // We are defining the function inside of another function to avoid creating
+ // global variables.
- var at, // The index of the current character
- ch, // The current character
- escapee = {
- '"': '"',
- '\\': '\\',
- '/': '/',
- b: '\b',
- f: '\f',
- n: '\n',
- r: '\r',
- t: '\t'
- },
- text,
+ var at, // The index of the current character
+ ch, // The current character
+ escapee = {
+ '"': '"',
+ "\\": "\\",
+ "/": "/",
+ b: "\b",
+ f: "\f",
+ n: "\n",
+ r: "\r",
+ t: "\t",
+ },
+ text,
+ error = function (m) {
+ // Call error when something is wrong.
- error = function (m) {
+ throw new SyntaxError(m);
+ },
+ next = function (c) {
+ // If a c parameter is provided, verify that it matches the current character.
-// Call error when something is wrong.
+ if (c && c !== ch) {
+ error("Expected '" + c + "' instead of '" + ch + "'");
+ }
- throw new SyntaxError(m);
- },
+ // Get the next character. When there are no more characters,
+ // return the empty string.
- next = function (c) {
+ ch = text.charAt(at);
+ at += 1;
+ return ch;
+ },
+ number = function () {
+ // Parse a number value.
-// If a c parameter is provided, verify that it matches the current character.
+ var number,
+ string = "";
- if (c && c !== ch) {
- error("Expected '" + c + "' instead of '" + ch + "'");
- }
+ if (ch === "-") {
+ string = "-";
+ next("-");
+ }
+ while (ch >= "0" && ch <= "9") {
+ string += ch;
+ next();
+ }
+ if (ch === ".") {
+ string += ".";
+ while (next() && ch >= "0" && ch <= "9") {
+ string += ch;
+ }
+ }
+ if (ch === "e" || ch === "E") {
+ string += ch;
+ next();
+ if (ch === "-" || ch === "+") {
+ string += ch;
+ next();
+ }
+ while (ch >= "0" && ch <= "9") {
+ string += ch;
+ next();
+ }
+ }
+ number = +string;
+ if (!isFinite(number)) {
+ error("Bad number");
+ } else if (number >= Int64.MAX_INT || number <= Int64.MIN_INT) {
+ // Return raw string for further process in TJSONProtocol
+ return string;
+ } else {
+ return number;
+ }
+ },
+ string = function () {
+ // Parse a string value.
-// Get the next character. When there are no more characters,
-// return the empty string.
+ var hex,
+ i,
+ string = "",
+ uffff;
- ch = text.charAt(at);
- at += 1;
- return ch;
- },
+ // When parsing for string values, we must look for " and \ characters.
- number = function () {
-
-// Parse a number value.
-
- var number,
- string = '';
-
- if (ch === '-') {
- string = '-';
- next('-');
- }
- while (ch >= '0' && ch <= '9') {
- string += ch;
- next();
- }
- if (ch === '.') {
- string += '.';
- while (next() && ch >= '0' && ch <= '9') {
- string += ch;
+ if (ch === '"') {
+ while (next()) {
+ if (ch === '"') {
+ next();
+ return string;
+ }
+ if (ch === "\\") {
+ next();
+ if (ch === "u") {
+ uffff = 0;
+ for (i = 0; i < 4; i += 1) {
+ hex = parseInt(next(), 16);
+ if (!isFinite(hex)) {
+ break;
}
- }
- if (ch === 'e' || ch === 'E') {
- string += ch;
- next();
- if (ch === '-' || ch === '+') {
- string += ch;
- next();
- }
- while (ch >= '0' && ch <= '9') {
- string += ch;
- next();
- }
- }
- number = +string;
- if (!isFinite(number)) {
- error("Bad number");
- } else if (number >= Int64.MAX_INT || number <= Int64.MIN_INT) {
- // Return raw string for further process in TJSONProtocol
- return string;
+ uffff = uffff * 16 + hex;
+ }
+ string += String.fromCharCode(uffff);
+ } else if (typeof escapee[ch] === "string") {
+ string += escapee[ch];
} else {
- return number;
+ break;
}
- },
-
- string = function () {
-
-// Parse a string value.
-
- var hex,
- i,
- string = '',
- uffff;
-
-// When parsing for string values, we must look for " and \ characters.
-
- if (ch === '"') {
- while (next()) {
- if (ch === '"') {
- next();
- return string;
- }
- if (ch === '\\') {
- next();
- if (ch === 'u') {
- uffff = 0;
- for (i = 0; i < 4; i += 1) {
- hex = parseInt(next(), 16);
- if (!isFinite(hex)) {
- break;
- }
- uffff = uffff * 16 + hex;
- }
- string += String.fromCharCode(uffff);
- } else if (typeof escapee[ch] === 'string') {
- string += escapee[ch];
- } else {
- break;
- }
- } else {
- string += ch;
- }
- }
- }
- error("Bad string");
- },
-
- white = function () {
-
-// Skip whitespace.
-
- while (ch && ch <= ' ') {
- next();
- }
- },
-
- word = function () {
-
-// true, false, or null.
-
- switch (ch) {
- case 't':
- next('t');
- next('r');
- next('u');
- next('e');
- return true;
- case 'f':
- next('f');
- next('a');
- next('l');
- next('s');
- next('e');
- return false;
- case 'n':
- next('n');
- next('u');
- next('l');
- next('l');
- return null;
- }
- error("Unexpected '" + ch + "'");
- },
-
- value, // Place holder for the value function.
-
- array = function () {
-
-// Parse an array value.
-
- var array = [];
-
- if (ch === '[') {
- next('[');
- white();
- if (ch === ']') {
- next(']');
- return array; // empty array
- }
- while (ch) {
- array.push(value());
- white();
- if (ch === ']') {
- next(']');
- return array;
- }
- next(',');
- white();
- }
- }
- error("Bad array");
- },
-
- object = function () {
-
-// Parse an object value.
-
- var key,
- object = {};
-
- if (ch === '{') {
- next('{');
- white();
- if (ch === '}') {
- next('}');
- return object; // empty object
- }
- while (ch) {
- key = string();
- white();
- next(':');
- if (Object.hasOwnProperty.call(object, key)) {
- error('Duplicate key "' + key + '"');
- }
- object[key] = value();
- white();
- if (ch === '}') {
- next('}');
- return object;
- }
- next(',');
- white();
- }
- }
- error("Bad object");
- };
-
- value = function () {
-
-// Parse a JSON value. It could be an object, an array, a string, a number,
-// or a word.
-
- white();
- switch (ch) {
- case '{':
- return object();
- case '[':
- return array();
- case '"':
- return string();
- case '-':
- return number();
- default:
- return ch >= '0' && ch <= '9'
- ? number()
- : word();
+ } else {
+ string += ch;
+ }
}
+ }
+ error("Bad string");
+ },
+ white = function () {
+ // Skip whitespace.
+
+ while (ch && ch <= " ") {
+ next();
+ }
+ },
+ word = function () {
+ // true, false, or null.
+
+ switch (ch) {
+ case "t":
+ next("t");
+ next("r");
+ next("u");
+ next("e");
+ return true;
+ case "f":
+ next("f");
+ next("a");
+ next("l");
+ next("s");
+ next("e");
+ return false;
+ case "n":
+ next("n");
+ next("u");
+ next("l");
+ next("l");
+ return null;
+ }
+ error("Unexpected '" + ch + "'");
+ },
+ value, // Place holder for the value function.
+ array = function () {
+ // Parse an array value.
+
+ var array = [];
+
+ if (ch === "[") {
+ next("[");
+ white();
+ if (ch === "]") {
+ next("]");
+ return array; // empty array
+ }
+ while (ch) {
+ array.push(value());
+ white();
+ if (ch === "]") {
+ next("]");
+ return array;
+ }
+ next(",");
+ white();
+ }
+ }
+ error("Bad array");
+ },
+ object = function () {
+ // Parse an object value.
+
+ var key,
+ object = {};
+
+ if (ch === "{") {
+ next("{");
+ white();
+ if (ch === "}") {
+ next("}");
+ return object; // empty object
+ }
+ while (ch) {
+ key = string();
+ white();
+ next(":");
+ if (Object.hasOwnProperty.call(object, key)) {
+ error('Duplicate key "' + key + '"');
+ }
+ object[key] = value();
+ white();
+ if (ch === "}") {
+ next("}");
+ return object;
+ }
+ next(",");
+ white();
+ }
+ }
+ error("Bad object");
};
-// Return the json_parse function. It will have access to all of the above
-// functions and variables.
+ value = function () {
+ // Parse a JSON value. It could be an object, an array, a string, a number,
+ // or a word.
- return function (source) {
- var result;
+ white();
+ switch (ch) {
+ case "{":
+ return object();
+ case "[":
+ return array();
+ case '"':
+ return string();
+ case "-":
+ return number();
+ default:
+ return ch >= "0" && ch <= "9" ? number() : word();
+ }
+ };
- text = source;
- at = 0;
- ch = ' ';
- result = value();
- white();
- if (ch) {
- error("Syntax error");
- }
+ // Return the json_parse function. It will have access to all of the above
+ // functions and variables.
- return result;
- };
-}());
+ return function (source) {
+ var result;
+
+ text = source;
+ at = 0;
+ ch = " ";
+ result = value();
+ white();
+ if (ch) {
+ error("Syntax error");
+ }
+
+ return result;
+ };
+})());
diff --git a/lib/nodejs/lib/thrift/json_protocol.js b/lib/nodejs/lib/thrift/json_protocol.js
index 7e2b7c9..31dcb81 100644
--- a/lib/nodejs/lib/thrift/json_protocol.js
+++ b/lib/nodejs/lib/thrift/json_protocol.js
@@ -17,15 +17,15 @@
* under the License.
*/
-var Int64 = require('node-int64');
-var Thrift = require('./thrift');
+var Int64 = require("node-int64");
+var Thrift = require("./thrift");
var Type = Thrift.Type;
var util = require("util");
-var Int64Util = require('./int64_util');
-var json_parse = require('./json_parse');
+var Int64Util = require("./int64_util");
+var json_parse = require("./json_parse");
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
module.exports = TJSONProtocol;
@@ -43,7 +43,7 @@
this.tstack = [];
this.tpos = [];
this.trans = trans;
-};
+}
/**
* Thrift IDL type Id to string mapping.
@@ -89,12 +89,12 @@
*/
TJSONProtocol.Version = 1;
-TJSONProtocol.prototype.flush = function() {
+TJSONProtocol.prototype.flush = function () {
this.writeToTransportIfStackIsFlushable();
return this.trans.flush();
};
-TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function() {
+TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function () {
if (this.tstack.length === 1) {
this.trans.write(this.tstack.pop());
}
@@ -106,20 +106,29 @@
* @param {Thrift.MessageType} messageType - The type of method call.
* @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
*/
-TJSONProtocol.prototype.writeMessageBegin = function(name, messageType, seqid) {
- this.tstack.push([TJSONProtocol.Version, '"' + name + '"', messageType, seqid]);
+TJSONProtocol.prototype.writeMessageBegin = function (
+ name,
+ messageType,
+ seqid,
+) {
+ this.tstack.push([
+ TJSONProtocol.Version,
+ '"' + name + '"',
+ messageType,
+ seqid,
+ ]);
};
/**
* Serializes the end of a Thrift RPC message.
*/
-TJSONProtocol.prototype.writeMessageEnd = function() {
+TJSONProtocol.prototype.writeMessageEnd = function () {
var obj = this.tstack.pop();
this.wobj = this.tstack.pop();
this.wobj.push(obj);
- this.wbuf = '[' + this.wobj.join(',') + ']';
+ this.wbuf = "[" + this.wobj.join(",") + "]";
// we assume there is nothing more to come so we write
this.trans.write(this.wbuf);
@@ -129,7 +138,7 @@
* Serializes the beginning of a struct.
* @param {string} name - The name of the struct.
*/
-TJSONProtocol.prototype.writeStructBegin = function(name) {
+TJSONProtocol.prototype.writeStructBegin = function (name) {
this.tpos.push(this.tstack.length);
this.tstack.push({});
};
@@ -137,22 +146,22 @@
/**
* Serializes the end of a struct.
*/
-TJSONProtocol.prototype.writeStructEnd = function() {
+TJSONProtocol.prototype.writeStructEnd = function () {
var p = this.tpos.pop();
var struct = this.tstack[p];
- var str = '{';
+ var str = "{";
var first = true;
for (var key in struct) {
if (first) {
first = false;
} else {
- str += ',';
+ str += ",";
}
- str += key + ':' + struct[key];
+ str += key + ":" + struct[key];
}
- str += '}';
+ str += "}";
this.tstack[p] = str;
this.writeToTransportIfStackIsFlushable();
@@ -164,26 +173,27 @@
* @param {Thrift.Protocol.Type} fieldType - The data type of the field.
* @param {number} fieldId - The field's unique identifier.
*/
-TJSONProtocol.prototype.writeFieldBegin = function(name, fieldType, fieldId) {
+TJSONProtocol.prototype.writeFieldBegin = function (name, fieldType, fieldId) {
this.tpos.push(this.tstack.length);
- this.tstack.push({ 'fieldId': '"' +
- fieldId + '"', 'fieldType': TJSONProtocol.Type[fieldType]
+ this.tstack.push({
+ fieldId: '"' + fieldId + '"',
+ fieldType: TJSONProtocol.Type[fieldType],
});
};
/**
* Serializes the end of a field.
*/
-TJSONProtocol.prototype.writeFieldEnd = function() {
+TJSONProtocol.prototype.writeFieldEnd = function () {
var value = this.tstack.pop();
var fieldInfo = this.tstack.pop();
- if (':' + value === ":[object Object]") {
- this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
- fieldInfo.fieldType + ':' + JSON.stringify(value) + '}';
+ if (":" + value === ":[object Object]") {
+ this.tstack[this.tstack.length - 1][fieldInfo.fieldId] =
+ "{" + fieldInfo.fieldType + ":" + JSON.stringify(value) + "}";
} else {
- this.tstack[this.tstack.length - 1][fieldInfo.fieldId] = '{' +
- fieldInfo.fieldType + ':' + value + '}';
+ this.tstack[this.tstack.length - 1][fieldInfo.fieldId] =
+ "{" + fieldInfo.fieldType + ":" + value + "}";
}
this.tpos.pop();
@@ -193,8 +203,7 @@
/**
* Serializes the end of the set of fields for a struct.
*/
-TJSONProtocol.prototype.writeFieldStop = function() {
-};
+TJSONProtocol.prototype.writeFieldStop = function () {};
/**
* Serializes the beginning of a map collection.
@@ -202,16 +211,20 @@
* @param {Thrift.Type} valType - The data type of the value.
* @param {number} [size] - The number of elements in the map (ignored).
*/
-TJSONProtocol.prototype.writeMapBegin = function(keyType, valType, size) {
+TJSONProtocol.prototype.writeMapBegin = function (keyType, valType, size) {
//size is invalid, we'll set it on end.
this.tpos.push(this.tstack.length);
- this.tstack.push([TJSONProtocol.Type[keyType], TJSONProtocol.Type[valType], 0]);
+ this.tstack.push([
+ TJSONProtocol.Type[keyType],
+ TJSONProtocol.Type[valType],
+ 0,
+ ]);
};
/**
* Serializes the end of a map.
*/
-TJSONProtocol.prototype.writeMapEnd = function() {
+TJSONProtocol.prototype.writeMapEnd = function () {
var p = this.tpos.pop();
if (p == this.tstack.length) {
@@ -219,14 +232,14 @@
}
if ((this.tstack.length - p - 1) % 2 !== 0) {
- this.tstack.push('');
+ this.tstack.push("");
}
var size = (this.tstack.length - p - 1) / 2;
this.tstack[p][this.tstack[p].length - 1] = size;
- var map = '}';
+ var map = "}";
var first = true;
while (this.tstack.length > p + 1) {
var v = this.tstack.pop();
@@ -234,16 +247,18 @@
if (first) {
first = false;
} else {
- map = ',' + map;
+ map = "," + map;
}
- if (! isNaN(k)) { k = '"' + k + '"'; } //json "keys" need to be strings
- map = k + ':' + v + map;
+ if (!isNaN(k)) {
+ k = '"' + k + '"';
+ } //json "keys" need to be strings
+ map = k + ":" + v + map;
}
- map = '{' + map;
+ map = "{" + map;
this.tstack[p].push(map);
- this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+ this.tstack[p] = "[" + this.tstack[p].join(",") + "]";
this.writeToTransportIfStackIsFlushable();
};
@@ -253,7 +268,7 @@
* @param {Thrift.Type} elemType - The data type of the elements.
* @param {number} size - The number of elements in the list.
*/
-TJSONProtocol.prototype.writeListBegin = function(elemType, size) {
+TJSONProtocol.prototype.writeListBegin = function (elemType, size) {
this.tpos.push(this.tstack.length);
this.tstack.push([TJSONProtocol.Type[elemType], size]);
};
@@ -261,7 +276,7 @@
/**
* Serializes the end of a list.
*/
-TJSONProtocol.prototype.writeListEnd = function() {
+TJSONProtocol.prototype.writeListEnd = function () {
var p = this.tpos.pop();
while (this.tstack.length > p + 1) {
@@ -270,7 +285,7 @@
this.tstack[p].push(tmpVal);
}
- this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+ this.tstack[p] = "[" + this.tstack[p].join(",") + "]";
this.writeToTransportIfStackIsFlushable();
};
@@ -280,15 +295,15 @@
* @param {Thrift.Type} elemType - The data type of the elements.
* @param {number} size - The number of elements in the list.
*/
-TJSONProtocol.prototype.writeSetBegin = function(elemType, size) {
- this.tpos.push(this.tstack.length);
- this.tstack.push([TJSONProtocol.Type[elemType], size]);
+TJSONProtocol.prototype.writeSetBegin = function (elemType, size) {
+ this.tpos.push(this.tstack.length);
+ this.tstack.push([TJSONProtocol.Type[elemType], size]);
};
/**
* Serializes the end of a set.
*/
-TJSONProtocol.prototype.writeSetEnd = function() {
+TJSONProtocol.prototype.writeSetEnd = function () {
var p = this.tpos.pop();
while (this.tstack.length > p + 1) {
@@ -297,33 +312,33 @@
this.tstack[p].push(tmpVal);
}
- this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+ this.tstack[p] = "[" + this.tstack[p].join(",") + "]";
this.writeToTransportIfStackIsFlushable();
};
/** Serializes a boolean */
-TJSONProtocol.prototype.writeBool = function(bool) {
+TJSONProtocol.prototype.writeBool = function (bool) {
this.tstack.push(bool ? 1 : 0);
};
/** Serializes a number */
-TJSONProtocol.prototype.writeByte = function(byte) {
+TJSONProtocol.prototype.writeByte = function (byte) {
this.tstack.push(byte);
};
/** Serializes a number */
-TJSONProtocol.prototype.writeI16 = function(i16) {
+TJSONProtocol.prototype.writeI16 = function (i16) {
this.tstack.push(i16);
};
/** Serializes a number */
-TJSONProtocol.prototype.writeI32 = function(i32) {
+TJSONProtocol.prototype.writeI32 = function (i32) {
this.tstack.push(i32);
};
/** Serializes a number */
-TJSONProtocol.prototype.writeI64 = function(i64) {
+TJSONProtocol.prototype.writeI64 = function (i64) {
if (i64 instanceof Int64) {
this.tstack.push(Int64Util.toDecimalString(i64));
} else {
@@ -332,69 +347,81 @@
};
/** Serializes a number */
-TJSONProtocol.prototype.writeDouble = function(dub) {
+TJSONProtocol.prototype.writeDouble = function (dub) {
this.tstack.push(dub);
};
/** Serializes a string */
-TJSONProtocol.prototype.writeString = function(arg) {
+TJSONProtocol.prototype.writeString = function (arg) {
// We do not encode uri components for wire transfer:
if (arg === null) {
- this.tstack.push(null);
+ this.tstack.push(null);
} else {
- if (typeof arg === 'string') {
- var str = arg;
- } else if (arg instanceof Buffer) {
- var str = arg.toString('utf8');
- } else {
- throw new Error('writeString called without a string/Buffer argument: ' + arg);
- }
+ if (typeof arg === "string") {
+ var str = arg;
+ } else if (arg instanceof Buffer) {
+ var str = arg.toString("utf8");
+ } else {
+ throw new Error(
+ "writeString called without a string/Buffer argument: " + arg,
+ );
+ }
- // concat may be slower than building a byte buffer
- var escapedString = '';
- for (var i = 0; i < str.length; i++) {
- var ch = str.charAt(i); // a single double quote: "
- if (ch === '\"') {
- escapedString += '\\\"'; // write out as: \"
- } else if (ch === '\\') { // a single backslash: \
- escapedString += '\\\\'; // write out as: \\
- /* Currently escaped forward slashes break TJSONProtocol.
- * As it stands, we can simply pass forward slashes into
- * our strings across the wire without being escaped.
- * I think this is the protocol's bug, not thrift.js
- * } else if(ch === '/') { // a single forward slash: /
- * escapedString += '\\/'; // write out as \/
- * }
- */
- } else if (ch === '\b') { // a single backspace: invisible
- escapedString += '\\b'; // write out as: \b"
- } else if (ch === '\f') { // a single formfeed: invisible
- escapedString += '\\f'; // write out as: \f"
- } else if (ch === '\n') { // a single newline: invisible
- escapedString += '\\n'; // write out as: \n"
- } else if (ch === '\r') { // a single return: invisible
- escapedString += '\\r'; // write out as: \r"
- } else if (ch === '\t') { // a single tab: invisible
- escapedString += '\\t'; // write out as: \t"
- } else {
- escapedString += ch; // Else it need not be escaped
- }
+ // concat may be slower than building a byte buffer
+ var escapedString = "";
+ for (var i = 0; i < str.length; i++) {
+ var ch = str.charAt(i); // a single double quote: "
+ if (ch === '\"') {
+ escapedString += '\\\"'; // write out as: \"
+ } else if (ch === "\\") {
+ // a single backslash: \
+ escapedString += "\\\\"; // write out as: \\
+ /* Currently escaped forward slashes break TJSONProtocol.
+ * As it stands, we can simply pass forward slashes into
+ * our strings across the wire without being escaped.
+ * I think this is the protocol's bug, not thrift.js
+ * } else if(ch === '/') { // a single forward slash: /
+ * escapedString += '\\/'; // write out as \/
+ * }
+ */
+ } else if (ch === "\b") {
+ // a single backspace: invisible
+ escapedString += "\\b"; // write out as: \b"
+ } else if (ch === "\f") {
+ // a single formfeed: invisible
+ escapedString += "\\f"; // write out as: \f"
+ } else if (ch === "\n") {
+ // a single newline: invisible
+ escapedString += "\\n"; // write out as: \n"
+ } else if (ch === "\r") {
+ // a single return: invisible
+ escapedString += "\\r"; // write out as: \r"
+ } else if (ch === "\t") {
+ // a single tab: invisible
+ escapedString += "\\t"; // write out as: \t"
+ } else {
+ escapedString += ch; // Else it need not be escaped
}
- this.tstack.push('"' + escapedString + '"');
+ }
+ this.tstack.push('"' + escapedString + '"');
}
};
/** Serializes a string */
-TJSONProtocol.prototype.writeBinary = function(arg) {
- if (typeof arg === 'string') {
- var buf = new Buffer(arg, 'binary');
- } else if (arg instanceof Buffer ||
- Object.prototype.toString.call(arg) == '[object Uint8Array]') {
+TJSONProtocol.prototype.writeBinary = function (arg) {
+ if (typeof arg === "string") {
+ var buf = new Buffer(arg, "binary");
+ } else if (
+ arg instanceof Buffer ||
+ Object.prototype.toString.call(arg) == "[object Uint8Array]"
+ ) {
var buf = arg;
} else {
- throw new Error('writeBinary called without a string/Buffer argument: ' + arg);
+ throw new Error(
+ "writeBinary called without a string/Buffer argument: " + arg,
+ );
}
- this.tstack.push('"' + buf.toString('base64') + '"');
+ this.tstack.push('"' + buf.toString("base64") + '"');
};
/**
@@ -408,7 +435,7 @@
* Deserializes the beginning of a message.
* @returns {AnonReadMessageBeginReturn}
*/
-TJSONProtocol.prototype.readMessageBegin = function() {
+TJSONProtocol.prototype.readMessageBegin = function () {
this.rstack = [];
this.rpos = [];
@@ -419,7 +446,8 @@
}
var cursor = transBuf.readIndex;
- if (transBuf.buf[cursor] !== 0x5B) { //[
+ if (transBuf.buf[cursor] !== 0x5b) {
+ //[
throw new Error("Malformed JSON input, no opening bracket");
}
@@ -432,22 +460,27 @@
var chr = transBuf.buf[cursor];
//we use hexa charcode here because data[i] returns an int and not a char
if (inString) {
- if (chr === 0x22) { //"
+ if (chr === 0x22) {
+ //"
inString = false;
- } else if (chr === 0x5C) { //\
+ } else if (chr === 0x5c) {
+ //\
//escaped character, skip
cursor += 1;
}
} else {
- if (chr === 0x5B) { //[
+ if (chr === 0x5b) {
+ //[
openBracketCount += 1;
- } else if (chr === 0x5D) { //]
+ } else if (chr === 0x5d) {
+ //]
openBracketCount -= 1;
if (openBracketCount === 0) {
//end of json message detected
break;
}
- } else if (chr === 0x22) { //"
+ } else if (chr === 0x22) {
+ //"
inString = true;
}
}
@@ -459,13 +492,15 @@
}
//Reconstitute the JSON object and conume the necessary bytes
- this.robj = json_parse(transBuf.buf.slice(transBuf.readIndex, cursor+1).toString());
+ this.robj = json_parse(
+ transBuf.buf.slice(transBuf.readIndex, cursor + 1).toString(),
+ );
this.trans.consume(cursor + 1 - transBuf.readIndex);
//Verify the protocol version
var version = this.robj.shift();
if (version != TJSONProtocol.Version) {
- throw new Error('Wrong thrift protocol version: ' + version);
+ throw new Error("Wrong thrift protocol version: " + version);
}
//Objectify the thrift message {name/type/sequence-number} for return
@@ -479,17 +514,16 @@
};
/** Deserializes the end of a message. */
-TJSONProtocol.prototype.readMessageEnd = function() {
-};
+TJSONProtocol.prototype.readMessageEnd = function () {};
/**
* Deserializes the beginning of a struct.
* @param {string} [name] - The name of the struct (ignored)
* @returns {object} - An object with an empty string fname property
*/
-TJSONProtocol.prototype.readStructBegin = function() {
+TJSONProtocol.prototype.readStructBegin = function () {
var r = {};
- r.fname = '';
+ r.fname = "";
//incase this is an array of structs
if (this.rstack[this.rstack.length - 1] instanceof Array) {
@@ -500,7 +534,7 @@
};
/** Deserializes the end of a struct. */
-TJSONProtocol.prototype.readStructEnd = function() {
+TJSONProtocol.prototype.readStructEnd = function () {
this.rstack.pop();
};
@@ -515,14 +549,14 @@
* Deserializes the beginning of a field.
* @returns {AnonReadFieldBeginReturn}
*/
-TJSONProtocol.prototype.readFieldBegin = function() {
+TJSONProtocol.prototype.readFieldBegin = function () {
var r = {};
var fid = -1;
var ftype = Type.STOP;
//get a fieldId
- for (var f in (this.rstack[this.rstack.length - 1])) {
+ for (var f in this.rstack[this.rstack.length - 1]) {
if (f === null) {
continue;
}
@@ -543,17 +577,18 @@
if (fid != -1) {
//should only be 1 of these but this is the only
//way to match a key
- for (var i in (this.rstack[this.rstack.length - 1])) {
+ for (var i in this.rstack[this.rstack.length - 1]) {
if (TJSONProtocol.RType[i] === null) {
continue;
}
ftype = TJSONProtocol.RType[i];
- this.rstack[this.rstack.length - 1] = this.rstack[this.rstack.length - 1][i];
+ this.rstack[this.rstack.length - 1] =
+ this.rstack[this.rstack.length - 1][i];
}
}
- r.fname = '';
+ r.fname = "";
r.ftype = ftype;
r.fid = fid;
@@ -561,7 +596,7 @@
};
/** Deserializes the end of a field. */
-TJSONProtocol.prototype.readFieldEnd = function() {
+TJSONProtocol.prototype.readFieldEnd = function () {
var pos = this.rpos.pop();
//get back to the right place in the stack
@@ -581,7 +616,7 @@
* Deserializes the beginning of a map.
* @returns {AnonReadMapBeginReturn}
*/
-TJSONProtocol.prototype.readMapBegin = function() {
+TJSONProtocol.prototype.readMapBegin = function () {
var map = this.rstack.pop();
var first = map.shift();
if (first instanceof Array) {
@@ -595,7 +630,6 @@
r.vtype = TJSONProtocol.RType[map.shift()];
r.size = map.shift();
-
this.rpos.push(this.rstack.length);
this.rstack.push(map.shift());
@@ -603,7 +637,7 @@
};
/** Deserializes the end of a map. */
-TJSONProtocol.prototype.readMapEnd = function() {
+TJSONProtocol.prototype.readMapEnd = function () {
this.readFieldEnd();
};
@@ -617,7 +651,7 @@
* Deserializes the beginning of a list.
* @returns {AnonReadColBeginReturn}
*/
-TJSONProtocol.prototype.readListBegin = function() {
+TJSONProtocol.prototype.readListBegin = function () {
var list = this.rstack[this.rstack.length - 1];
var r = {};
@@ -631,7 +665,7 @@
};
/** Deserializes the end of a list. */
-TJSONProtocol.prototype.readListEnd = function() {
+TJSONProtocol.prototype.readListEnd = function () {
var pos = this.rpos.pop() - 2;
var st = this.rstack;
st.pop();
@@ -644,33 +678,33 @@
* Deserializes the beginning of a set.
* @returns {AnonReadColBeginReturn}
*/
-TJSONProtocol.prototype.readSetBegin = function() {
+TJSONProtocol.prototype.readSetBegin = function () {
return this.readListBegin();
};
/** Deserializes the end of a set. */
-TJSONProtocol.prototype.readSetEnd = function() {
+TJSONProtocol.prototype.readSetEnd = function () {
return this.readListEnd();
};
-TJSONProtocol.prototype.readBool = function() {
- return this.readValue() == '1';
+TJSONProtocol.prototype.readBool = function () {
+ return this.readValue() == "1";
};
-TJSONProtocol.prototype.readByte = function() {
+TJSONProtocol.prototype.readByte = function () {
return this.readI32();
};
-TJSONProtocol.prototype.readI16 = function() {
+TJSONProtocol.prototype.readI16 = function () {
return this.readI32();
};
-TJSONProtocol.prototype.readI32 = function(f) {
+TJSONProtocol.prototype.readI32 = function (f) {
return +this.readValue();
-}
+};
/** Returns the next value found in the protocol buffer */
-TJSONProtocol.prototype.readValue = function(f) {
+TJSONProtocol.prototype.readValue = function (f) {
if (f === undefined) {
f = this.rstack[this.rstack.length - 1];
}
@@ -702,9 +736,9 @@
return r.value;
};
-TJSONProtocol.prototype.readI64 = function() {
- var n = this.readValue()
- if (typeof n === 'string') {
+TJSONProtocol.prototype.readI64 = function () {
+ var n = this.readValue();
+ if (typeof n === "string") {
// Assuming no one is sending in 1.11111e+33 format
return Int64Util.fromDecimalString(n);
} else {
@@ -712,15 +746,15 @@
}
};
-TJSONProtocol.prototype.readDouble = function() {
+TJSONProtocol.prototype.readDouble = function () {
return this.readI32();
};
-TJSONProtocol.prototype.readBinary = function() {
- return new Buffer(this.readValue(), 'base64');
+TJSONProtocol.prototype.readBinary = function () {
+ return new Buffer(this.readValue(), "base64");
};
-TJSONProtocol.prototype.readString = function() {
+TJSONProtocol.prototype.readString = function () {
return this.readValue();
};
@@ -729,15 +763,15 @@
* @readonly
* @returns {Thrift.Transport} The underlying transport.
*/
-TJSONProtocol.prototype.getTransport = function() {
+TJSONProtocol.prototype.getTransport = function () {
return this.trans;
};
/**
* Method to arbitrarily skip over data
*/
-TJSONProtocol.prototype.skip = function(type) {
- switch (type) {
+TJSONProtocol.prototype.skip = function (type) {
+ switch (type) {
case Type.BOOL:
this.readBool();
break;
@@ -794,6 +828,6 @@
this.readListEnd();
break;
default:
- throw new Error("Invalid type: " + type);
+ throw new Error("Invalid type: " + type);
}
};
diff --git a/lib/nodejs/lib/thrift/log.js b/lib/nodejs/lib/thrift/log.js
index 053e813..82d8a22 100644
--- a/lib/nodejs/lib/thrift/log.js
+++ b/lib/nodejs/lib/thrift/log.js
@@ -17,17 +17,17 @@
* under the License.
*/
-var util = require('util');
+var util = require("util");
var disabled = function () {};
var logFunc = console.log;
-var logLevel = 'error'; // default level
+var logLevel = "error"; // default level
function factory(level) {
return function () {
// better use spread syntax, but due to compatibility,
// use legacy method here.
- var args = ['thrift: [' + level + '] '].concat(Array.from(arguments));
+ var args = ["thrift: [" + level + "] "].concat(Array.from(arguments));
return logFunc(util.format.apply(null, args));
};
}
@@ -42,22 +42,22 @@
logFunc = func;
};
-var setLogLevel = exports.setLogLevel = function (level) {
+var setLogLevel = (exports.setLogLevel = function (level) {
trace = debug = error = warning = info = disabled;
logLevel = level;
switch (logLevel) {
- case 'trace':
- trace = factory('TRACE');
- case 'debug':
- debug = factory('DEBUG');
- case 'error':
- error = factory('ERROR');
- case 'warning':
- warning = factory('WARN');
- case 'info':
- info = factory('INFO');
+ case "trace":
+ trace = factory("TRACE");
+ case "debug":
+ debug = factory("DEBUG");
+ case "error":
+ error = factory("ERROR");
+ case "warning":
+ warning = factory("WARN");
+ case "info":
+ info = factory("INFO");
}
-};
+});
// set default
setLogLevel(logLevel);
diff --git a/lib/nodejs/lib/thrift/multiplexed_processor.js b/lib/nodejs/lib/thrift/multiplexed_processor.js
index 67b62f7..864d66d 100644
--- a/lib/nodejs/lib/thrift/multiplexed_processor.js
+++ b/lib/nodejs/lib/thrift/multiplexed_processor.js
@@ -16,31 +16,38 @@
* specific language governing permissions and limitations
* under the License.
*/
-var Thrift = require('./thrift');
+var Thrift = require("./thrift");
exports.MultiplexedProcessor = MultiplexedProcessor;
function MultiplexedProcessor(stream, options) {
this.services = {};
-};
+}
-MultiplexedProcessor.prototype.registerProcessor = function(name, handler) {
+MultiplexedProcessor.prototype.registerProcessor = function (name, handler) {
this.services[name] = handler;
};
-MultiplexedProcessor.prototype.process = function(inp, out) {
+MultiplexedProcessor.prototype.process = function (inp, out) {
var begin = inp.readMessageBegin();
- if (begin.mtype != Thrift.MessageType.CALL && begin.mtype != Thrift.MessageType.ONEWAY) {
- throw new Thrift.TException('TMultiplexedProcessor: Unexpected message type');
+ if (
+ begin.mtype != Thrift.MessageType.CALL &&
+ begin.mtype != Thrift.MessageType.ONEWAY
+ ) {
+ throw new Thrift.TException(
+ "TMultiplexedProcessor: Unexpected message type",
+ );
}
- var p = begin.fname.split(':');
+ var p = begin.fname.split(":");
var sname = p[0];
var fname = p[1];
- if (! (sname in this.services)) {
- throw new Thrift.TException('TMultiplexedProcessor: Unknown service: ' + sname);
+ if (!(sname in this.services)) {
+ throw new Thrift.TException(
+ "TMultiplexedProcessor: Unknown service: " + sname,
+ );
}
//construct a proxy object which stubs the readMessageBegin
@@ -51,11 +58,11 @@
inpProxy[attr] = inp[attr];
}
- inpProxy.readMessageBegin = function() {
+ inpProxy.readMessageBegin = function () {
return {
fname: fname,
mtype: begin.mtype,
- rseqid: begin.rseqid
+ rseqid: begin.rseqid,
};
};
diff --git a/lib/nodejs/lib/thrift/multiplexed_protocol.js b/lib/nodejs/lib/thrift/multiplexed_protocol.js
index d078aa2..1d2df96 100644
--- a/lib/nodejs/lib/thrift/multiplexed_protocol.js
+++ b/lib/nodejs/lib/thrift/multiplexed_protocol.js
@@ -16,55 +16,69 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var Thrift = require('./thrift');
+var util = require("util");
+var Thrift = require("./thrift");
exports.Multiplexer = Multiplexer;
function Wrapper(serviceName, protocol, connection) {
-
function MultiplexProtocol(trans, strictRead, strictWrite) {
protocol.call(this, trans, strictRead, strictWrite);
- };
+ }
util.inherits(MultiplexProtocol, protocol);
- MultiplexProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
+ MultiplexProtocol.prototype.writeMessageBegin = function (name, type, seqid) {
if (type == Thrift.MessageType.CALL || type == Thrift.MessageType.ONEWAY) {
connection.seqId2Service[seqid] = serviceName;
- MultiplexProtocol.super_.prototype.writeMessageBegin.call(this,
- serviceName + ":" + name,
- type,
- seqid);
+ MultiplexProtocol.super_.prototype.writeMessageBegin.call(
+ this,
+ serviceName + ":" + name,
+ type,
+ seqid,
+ );
} else {
- MultiplexProtocol.super_.prototype.writeMessageBegin.call(this, name, type, seqid);
+ MultiplexProtocol.super_.prototype.writeMessageBegin.call(
+ this,
+ name,
+ type,
+ seqid,
+ );
}
};
return MultiplexProtocol;
-};
+}
function Multiplexer() {
this.seqid = 0;
-};
+}
-Multiplexer.prototype.createClient = function(serviceName, ServiceClient, connection) {
+Multiplexer.prototype.createClient = function (
+ serviceName,
+ ServiceClient,
+ connection,
+) {
if (ServiceClient.Client) {
ServiceClient = ServiceClient.Client;
}
- var writeCb = function(buf, seqid) {
- connection.write(buf,seqid);
+ var writeCb = function (buf, seqid) {
+ connection.write(buf, seqid);
};
var transport = new connection.transport(undefined, writeCb);
- var protocolWrapper = new Wrapper(serviceName, connection.protocol, connection);
+ var protocolWrapper = new Wrapper(
+ serviceName,
+ connection.protocol,
+ connection,
+ );
var client = new ServiceClient(transport, protocolWrapper);
var self = this;
- client.new_seqid = function() {
+ client.new_seqid = function () {
self.seqid += 1;
return self.seqid;
};
- if (typeof connection.client !== 'object') {
+ if (typeof connection.client !== "object") {
connection.client = {};
}
connection.client[serviceName] = client;
diff --git a/lib/nodejs/lib/thrift/ohos_connection.js b/lib/nodejs/lib/thrift/ohos_connection.js
index 95bf122..34afaae 100644
--- a/lib/nodejs/lib/thrift/ohos_connection.js
+++ b/lib/nodejs/lib/thrift/ohos_connection.js
@@ -16,15 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var EventEmitter = require('events').EventEmitter;
-var thrift = require('./thrift');
+var util = require("util");
+var EventEmitter = require("events").EventEmitter;
+var thrift = require("./thrift");
-var TBufferedTransport = require('./buffered_transport');
-var TBinaryProtocol = require('./binary_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TBinaryProtocol = require("./binary_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
-var createClient = require('./create_client');
+var createClient = require("./create_client");
/**
* @class
@@ -69,7 +69,7 @@
* semantics implemented over the OpenHarmonyOS http.request() method.
* @see {@link createOhosConnection}
*/
-var OhosConnection = exports.OhosConnection = function(options) {
+var OhosConnection = (exports.OhosConnection = function (options) {
//Initialize the emitter base object
EventEmitter.call(this);
@@ -78,12 +78,12 @@
this.options = options || {};
this.host = this.options.host;
this.port = this.options.port;
- this.path = this.options.path || '/';
+ this.path = this.options.path || "/";
//OpenHarmonyOS needs URL for initiating an HTTP request.
this.url =
this.port === 80
- ? this.host.replace(/\/$/, '') + this.path
- : this.host.replace(/\/$/, '') + ':' + this.port + this.path;
+ ? this.host.replace(/\/$/, "") + this.path
+ : this.host.replace(/\/$/, "") + ":" + this.port + this.path;
this.transport = this.options.transport || TBufferedTransport;
this.protocol = this.options.protocol || TBinaryProtocol;
//Inherit method from OpenHarmonyOS HTTP module
@@ -91,17 +91,17 @@
//Prepare HTTP request options
this.requestOptions = {
- method: 'POST',
+ method: "POST",
header: this.options.header || {},
readTimeout: this.options.readTimeout || 60000,
- connectTimeout: this.options.connectTimeout || 60000
+ connectTimeout: this.options.connectTimeout || 60000,
};
for (var attrname in this.options.requestOptions) {
this.requestOptions[attrname] = this.options.requestOptions[attrname];
}
/*jshint -W069 */
- if (!this.requestOptions.header['Connection']) {
- this.requestOptions.header['Connection'] = 'keep-alive';
+ if (!this.requestOptions.header["Connection"]) {
+ this.requestOptions.header["Connection"] = "keep-alive";
}
/*jshint +W069 */
@@ -134,60 +134,61 @@
delete self.seqId2Service[header.rseqid];
}
/*jshint -W083 */
- client._reqs[dummy_seqid] = function(err, success){
+ client._reqs[dummy_seqid] = function (err, success) {
transport_with_data.commitPosition();
var clientCallback = client._reqs[header.rseqid];
delete client._reqs[header.rseqid];
if (clientCallback) {
- process.nextTick(function() {
+ process.nextTick(function () {
clientCallback(err, success);
});
}
};
/*jshint +W083 */
- if(client['recv_' + header.fname]) {
- client['recv_' + header.fname](proto, header.mtype, dummy_seqid);
+ if (client["recv_" + header.fname]) {
+ client["recv_" + header.fname](proto, header.mtype, dummy_seqid);
} else {
delete client._reqs[dummy_seqid];
- self.emit("error",
- new thrift.TApplicationException(
- thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
- "Received a response to an unknown RPC function"));
+ self.emit(
+ "error",
+ new thrift.TApplicationException(
+ thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
+ "Received a response to an unknown RPC function",
+ ),
+ );
}
}
- }
- catch (e) {
+ } catch (e) {
if (e instanceof InputBufferUnderrunError) {
transport_with_data.rollbackPosition();
} else {
- self.emit('error', e);
+ self.emit("error", e);
}
}
}
-
//Response handler
//////////////////////////////////////////////////
- this.responseCallback = function(error, response) {
+ this.responseCallback = function (error, response) {
//Response will be a struct like:
// https://developer.harmonyos.com/en/docs/documentation/doc-references/js-apis-net-http-0000001168304341#section15920192914312
var data = [];
var dataLen = 0;
if (error) {
- self.emit('error', error);
+ self.emit("error", error);
return;
}
if (!response || response.responseCode !== 200) {
- self.emit('error', new THTTPException(response));
+ self.emit("error", new THTTPException(response));
}
// With OpenHarmonyOS running in a Browser (e.g. Browserify), chunk
// will be a string or an ArrayBuffer.
if (
- typeof response.result == 'string' ||
- Object.prototype.toString.call(response.result) == '[object Uint8Array]'
+ typeof response.result == "string" ||
+ Object.prototype.toString.call(response.result) == "[object Uint8Array]"
) {
// Wrap ArrayBuffer/string in a Buffer so data[i].copy will work
data.push(Buffer.from(response.result));
@@ -211,7 +212,7 @@
* @event {error} the "error" event is raised upon request failure passing the
* Node.js error object to the listener.
*/
- this.write = function(data) {
+ this.write = function (data) {
//To initiate multiple HTTP requests, we must create an HttpRequest object
// for each HTTP request
var http = self.createHttp();
@@ -223,7 +224,7 @@
opts.extraData = data.toString();
http.request(self.url, opts, self.responseCallback);
};
-};
+});
util.inherits(OhosConnection, EventEmitter);
/**
@@ -236,7 +237,7 @@
* @returns {OhosConnection} The connection object.
* @see {@link ConnectOptions}
*/
-exports.createOhosConnection = function(createHttp, host, port, options) {
+exports.createOhosConnection = function (createHttp, host, port, options) {
options.createHttp = createHttp;
options.host = host;
options.port = port || 80;
@@ -256,6 +257,6 @@
this.response = response;
this.type = thrift.TApplicationExceptionType.PROTOCOL_ERROR;
this.message =
- 'Received a response with a bad HTTP status code: ' + response.responseCode;
+ "Received a response with a bad HTTP status code: " + response.responseCode;
}
util.inherits(THTTPException, thrift.TApplicationException);
diff --git a/lib/nodejs/lib/thrift/protocol.js b/lib/nodejs/lib/thrift/protocol.js
index a70ebe2..6eb88da 100644
--- a/lib/nodejs/lib/thrift/protocol.js
+++ b/lib/nodejs/lib/thrift/protocol.js
@@ -17,6 +17,6 @@
* under the License.
*/
-module.exports.TBinaryProtocol = require('./binary_protocol');
-module.exports.TCompactProtocol = require('./compact_protocol');
-module.exports.TJSONProtocol = require('./json_protocol');
+module.exports.TBinaryProtocol = require("./binary_protocol");
+module.exports.TCompactProtocol = require("./compact_protocol");
+module.exports.TJSONProtocol = require("./json_protocol");
diff --git a/lib/nodejs/lib/thrift/server.js b/lib/nodejs/lib/thrift/server.js
index 16b74ea..80a369f 100644
--- a/lib/nodejs/lib/thrift/server.js
+++ b/lib/nodejs/lib/thrift/server.js
@@ -17,14 +17,14 @@
* under the License.
*/
-var constants = require('constants');
-var net = require('net');
-var tls = require('tls');
+var constants = require("constants");
+var net = require("net");
+var tls = require("tls");
-var TBufferedTransport = require('./buffered_transport');
-var TBinaryProtocol = require('./binary_protocol');
-var THeaderProtocol = require('./header_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TBinaryProtocol = require("./binary_protocol");
+var THeaderProtocol = require("./header_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
/**
* Create a Thrift server which can serve one or multiple services.
@@ -33,75 +33,82 @@
* @param {ServerOptions} options - Optional additional server configuration.
* @returns {object} - The Apache Thrift Multiplex Server.
*/
-exports.createMultiplexServer = function(processor, options) {
- var transport = (options && options.transport) ? options.transport : TBufferedTransport;
- var protocol = (options && options.protocol) ? options.protocol : TBinaryProtocol;
+exports.createMultiplexServer = function (processor, options) {
+ var transport =
+ options && options.transport ? options.transport : TBufferedTransport;
+ var protocol =
+ options && options.protocol ? options.protocol : TBinaryProtocol;
function serverImpl(stream) {
var self = this;
- stream.on('error', function(err) {
- self.emit('error', err);
+ stream.on("error", function (err) {
+ self.emit("error", err);
});
- stream.on('data', transport.receiver(function(transportWithData) {
- var input = new protocol(transportWithData);
- var outputCb = function(buf) {
- try {
+ stream.on(
+ "data",
+ transport.receiver(function (transportWithData) {
+ var input = new protocol(transportWithData);
+ var outputCb = function (buf) {
+ try {
stream.write(buf);
- } catch (err) {
- self.emit('error', err);
+ } catch (err) {
+ self.emit("error", err);
stream.end();
- }
- };
+ }
+ };
- var output = new protocol(new transport(undefined, outputCb));
- // Read and write need to be performed on the same transport
- // for THeaderProtocol because we should only respond with
- // headers if the request contains headers
- if (protocol === THeaderProtocol) {
- output = input;
- output.trans.onFlush = outputCb;
- }
+ var output = new protocol(new transport(undefined, outputCb));
+ // Read and write need to be performed on the same transport
+ // for THeaderProtocol because we should only respond with
+ // headers if the request contains headers
+ if (protocol === THeaderProtocol) {
+ output = input;
+ output.trans.onFlush = outputCb;
+ }
- try {
- do {
- processor.process(input, output);
- transportWithData.commitPosition();
- } while (true);
- } catch (err) {
- if (err instanceof InputBufferUnderrunError) {
- //The last data in the buffer was not a complete message, wait for the rest
- transportWithData.rollbackPosition();
+ try {
+ do {
+ processor.process(input, output);
+ transportWithData.commitPosition();
+ } while (true);
+ } catch (err) {
+ if (err instanceof InputBufferUnderrunError) {
+ //The last data in the buffer was not a complete message, wait for the rest
+ transportWithData.rollbackPosition();
+ } else if (err.message === "Invalid type: undefined") {
+ //No more data in the buffer
+ //This trap is a bit hackish
+ //The next step to improve the node behavior here is to have
+ // the compiler generated process method throw a more explicit
+ // error when the network buffer is empty (regardles of the
+ // protocol/transport stack in use) and replace this heuristic.
+ // Also transports should probably not force upper layers to
+ // manage their buffer positions (i.e. rollbackPosition() and
+ // commitPosition() should be eliminated in lieu of a transport
+ // encapsulated buffer management strategy.)
+ transportWithData.rollbackPosition();
+ } else {
+ //Unexpected error
+ self.emit("error", err);
+ stream.end();
+ }
}
- else if (err.message === "Invalid type: undefined") {
- //No more data in the buffer
- //This trap is a bit hackish
- //The next step to improve the node behavior here is to have
- // the compiler generated process method throw a more explicit
- // error when the network buffer is empty (regardles of the
- // protocol/transport stack in use) and replace this heuristic.
- // Also transports should probably not force upper layers to
- // manage their buffer positions (i.e. rollbackPosition() and
- // commitPosition() should be eliminated in lieu of a transport
- // encapsulated buffer management strategy.)
- transportWithData.rollbackPosition();
- }
- else {
- //Unexpected error
- self.emit('error', err);
- stream.end();
- }
- }
- }));
+ }),
+ );
- stream.on('end', function() {
+ stream.on("end", function () {
stream.end();
});
}
if (options && options.tls) {
- if (!('secureProtocol' in options.tls) && !('secureOptions' in options.tls)) {
+ if (
+ !("secureProtocol" in options.tls) &&
+ !("secureOptions" in options.tls)
+ ) {
options.tls.secureProtocol = "SSLv23_method";
- options.tls.secureOptions = constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3;
+ options.tls.secureOptions =
+ constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3;
}
return tls.createServer(options.tls, serverImpl);
} else {
@@ -115,7 +122,7 @@
* @param {ServerOptions} options - Optional additional server configuration.
* @returns {object} - The Apache Thrift Multiplex Server.
*/
-exports.createServer = function(processor, handler, options) {
+exports.createServer = function (processor, handler, options) {
if (processor.Processor) {
processor = processor.Processor;
}
diff --git a/lib/nodejs/lib/thrift/thrift.js b/lib/nodejs/lib/thrift/thrift.js
index 3a693f6..741a493 100644
--- a/lib/nodejs/lib/thrift/thrift.js
+++ b/lib/nodejs/lib/thrift/thrift.js
@@ -16,9 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
+var util = require("util");
-var Type = exports.Type = {
+var Type = (exports.Type = {
STOP: 0,
VOID: 1,
BOOL: 2,
@@ -35,14 +35,14 @@
SET: 14,
LIST: 15,
UTF8: 16,
- UTF16: 17
-};
+ UTF16: 17,
+});
exports.MessageType = {
CALL: 1,
REPLY: 2,
EXCEPTION: 3,
- ONEWAY: 4
+ ONEWAY: 4,
};
exports.TException = TException;
@@ -55,10 +55,10 @@
this.name = this.constructor.name;
this.message = message;
-};
+}
util.inherits(TException, Error);
-var TApplicationExceptionType = exports.TApplicationExceptionType = {
+var TApplicationExceptionType = (exports.TApplicationExceptionType = {
UNKNOWN: 0,
UNKNOWN_METHOD: 1,
INVALID_MESSAGE_TYPE: 2,
@@ -69,8 +69,8 @@
PROTOCOL_ERROR: 7,
INVALID_TRANSFORM: 8,
INVALID_PROTOCOL: 9,
- UNSUPPORTED_CLIENT_TYPE: 10
-};
+ UNSUPPORTED_CLIENT_TYPE: 10,
+});
exports.TApplicationException = TApplicationException;
@@ -83,73 +83,73 @@
this.type = type || TApplicationExceptionType.UNKNOWN;
this.name = this.constructor.name;
this.message = message;
-};
+}
util.inherits(TApplicationException, TException);
-TApplicationException.prototype[Symbol.for("read")] = TApplicationException.prototype.read = function(input) {
- var ftype;
- var ret = input.readStructBegin('TApplicationException');
+TApplicationException.prototype[Symbol.for("read")] =
+ TApplicationException.prototype.read = function (input) {
+ var ftype;
+ var ret = input.readStructBegin("TApplicationException");
- while(1){
+ while (1) {
ret = input.readFieldBegin();
- if(ret.ftype == Type.STOP)
- break;
+ if (ret.ftype == Type.STOP) break;
- switch(ret.fid){
- case 1:
- if( ret.ftype == Type.STRING ){
- ret = input.readString();
- this.message = ret;
- } else {
- ret = input.skip(ret.ftype);
- }
- break;
- case 2:
- if( ret.ftype == Type.I32 ){
- ret = input.readI32();
- this.type = ret;
- } else {
- ret = input.skip(ret.ftype);
- }
- break;
- default:
- ret = input.skip(ret.ftype);
- break;
+ switch (ret.fid) {
+ case 1:
+ if (ret.ftype == Type.STRING) {
+ ret = input.readString();
+ this.message = ret;
+ } else {
+ ret = input.skip(ret.ftype);
+ }
+ break;
+ case 2:
+ if (ret.ftype == Type.I32) {
+ ret = input.readI32();
+ this.type = ret;
+ } else {
+ ret = input.skip(ret.ftype);
+ }
+ break;
+ default:
+ ret = input.skip(ret.ftype);
+ break;
}
input.readFieldEnd();
- }
- input.readStructEnd();
-};
+ }
+ input.readStructEnd();
+ };
-TApplicationException.prototype[Symbol.for("write")] = TApplicationException.prototype.write = function(output){
- output.writeStructBegin('TApplicationException');
+TApplicationException.prototype[Symbol.for("write")] =
+ TApplicationException.prototype.write = function (output) {
+ output.writeStructBegin("TApplicationException");
- if (this.message) {
- output.writeFieldBegin('message', Type.STRING, 1);
+ if (this.message) {
+ output.writeFieldBegin("message", Type.STRING, 1);
output.writeString(this.message);
output.writeFieldEnd();
- }
+ }
- if (this.code) {
- output.writeFieldBegin('type', Type.I32, 2);
+ if (this.code) {
+ output.writeFieldBegin("type", Type.I32, 2);
output.writeI32(this.code);
output.writeFieldEnd();
- }
+ }
- output.writeFieldStop();
- output.writeStructEnd();
-};
+ output.writeFieldStop();
+ output.writeStructEnd();
+ };
-var TProtocolExceptionType = exports.TProtocolExceptionType = {
+var TProtocolExceptionType = (exports.TProtocolExceptionType = {
UNKNOWN: 0,
INVALID_DATA: 1,
NEGATIVE_SIZE: 2,
SIZE_LIMIT: 3,
BAD_VERSION: 4,
NOT_IMPLEMENTED: 5,
- DEPTH_LIMIT: 6
-};
-
+ DEPTH_LIMIT: 6,
+});
exports.TProtocolException = TProtocolException;
@@ -162,74 +162,74 @@
this.name = this.constructor.name;
this.type = type;
this.message = message;
-};
+}
util.inherits(TProtocolException, Error);
-exports.objectLength = function(obj) {
+exports.objectLength = function (obj) {
return Object.keys(obj).length;
};
-exports.inherits = function(constructor, superConstructor) {
+exports.inherits = function (constructor, superConstructor) {
util.inherits(constructor, superConstructor);
};
var copyList, copyMap;
-copyList = function(lst, types) {
-
- if (!lst) {return lst; }
+copyList = function (lst, types) {
+ if (!lst) {
+ return lst;
+ }
var type;
if (types.shift === undefined) {
type = types;
- }
- else {
+ } else {
type = types[0];
}
var Type = type;
- var len = lst.length, result = [], i, val;
+ var len = lst.length,
+ result = [],
+ i,
+ val;
for (i = 0; i < len; i++) {
val = lst[i];
if (type === null) {
result.push(val);
- }
- else if (type === copyMap || type === copyList) {
+ } else if (type === copyMap || type === copyList) {
result.push(type(val, types.slice(1)));
- }
- else {
+ } else {
result.push(new Type(val));
}
}
return result;
};
-copyMap = function(obj, types){
-
- if (!obj) {return obj; }
+copyMap = function (obj, types) {
+ if (!obj) {
+ return obj;
+ }
var type;
if (types.shift === undefined) {
type = types;
- }
- else {
+ } else {
type = types[0];
}
var Type = type;
- var result = {}, val;
- for(var prop in obj) {
- if(obj.hasOwnProperty(prop)) {
+ var result = {},
+ val;
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
val = obj[prop];
if (type === null) {
result[prop] = val;
- }
- else if (type === copyMap || type === copyList) {
+ } else if (type === copyMap || type === copyList) {
result[prop] = type(val, types.slice(1));
- }
- else {
+ } else {
result[prop] = new Type(val);
}
}
diff --git a/lib/nodejs/lib/thrift/transport.js b/lib/nodejs/lib/thrift/transport.js
index 59daa98..b3ba394 100644
--- a/lib/nodejs/lib/thrift/transport.js
+++ b/lib/nodejs/lib/thrift/transport.js
@@ -17,6 +17,6 @@
* under the License.
*/
-module.exports.TBufferedTransport = require('./buffered_transport');
-module.exports.TFramedTransport = require('./framed_transport');
-module.exports.InputBufferUnderrunError = require('./input_buffer_underrun_error');
+module.exports.TBufferedTransport = require("./buffered_transport");
+module.exports.TFramedTransport = require("./framed_transport");
+module.exports.InputBufferUnderrunError = require("./input_buffer_underrun_error");
diff --git a/lib/nodejs/lib/thrift/web_server.js b/lib/nodejs/lib/thrift/web_server.js
index a33f47a..f49f654 100644
--- a/lib/nodejs/lib/thrift/web_server.js
+++ b/lib/nodejs/lib/thrift/web_server.js
@@ -16,19 +16,20 @@
* specific language governing permissions and limitations
* under the License.
*/
-var http = require('http');
-var https = require('https');
+var http = require("http");
+var https = require("https");
var url = require("url");
var path = require("path");
var fs = require("fs");
var crypto = require("crypto");
-var log = require('./log');
+var log = require("./log");
-var MultiplexedProcessor = require('./multiplexed_processor').MultiplexedProcessor;
+var MultiplexedProcessor =
+ require("./multiplexed_processor").MultiplexedProcessor;
-var TBufferedTransport = require('./buffered_transport');
-var TBinaryProtocol = require('./binary_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TBinaryProtocol = require("./binary_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
// WSFrame constructor and prototype
/////////////////////////////////////////////////////////////////////
@@ -82,36 +83,43 @@
* @param {Boolean} binEncoding - True for binary encoding, false for text encoding
* @returns {Buffer} - The WebSocket frame, ready to send
*/
- encode: function(data, mask, binEncoding) {
- var frame = new Buffer(wsFrame.frameSizeFromData(data, mask));
- //Byte 0 - FIN & OPCODE
- frame[0] = wsFrame.fin.FIN +
- (binEncoding ? wsFrame.frameOpCodes.BIN : wsFrame.frameOpCodes.TEXT);
- //Byte 1 or 1-3 or 1-9 - MASK FLAG & SIZE
- var payloadOffset = 2;
- if (data.length < 0x7E) {
- frame[1] = data.length + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
- } else if (data.length < 0xFFFF) {
- frame[1] = 0x7E + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
- frame.writeUInt16BE(data.length, 2, true);
- payloadOffset = 4;
- } else {
- frame[1] = 0x7F + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
- frame.writeUInt32BE(0, 2, true);
- frame.writeUInt32BE(data.length, 6, true);
- payloadOffset = 10;
- }
- //MASK
- if (mask) {
- mask.copy(frame, payloadOffset, 0, 4);
- payloadOffset += 4;
- }
- //Payload
- data.copy(frame, payloadOffset);
- if (mask) {
- wsFrame.applyMask(frame.slice(payloadOffset), frame.slice(payloadOffset-4,payloadOffset));
- }
- return frame;
+ encode: function (data, mask, binEncoding) {
+ var frame = new Buffer(wsFrame.frameSizeFromData(data, mask));
+ //Byte 0 - FIN & OPCODE
+ frame[0] =
+ wsFrame.fin.FIN +
+ (binEncoding ? wsFrame.frameOpCodes.BIN : wsFrame.frameOpCodes.TEXT);
+ //Byte 1 or 1-3 or 1-9 - MASK FLAG & SIZE
+ var payloadOffset = 2;
+ if (data.length < 0x7e) {
+ frame[1] =
+ data.length + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
+ } else if (data.length < 0xffff) {
+ frame[1] =
+ 0x7e + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
+ frame.writeUInt16BE(data.length, 2, true);
+ payloadOffset = 4;
+ } else {
+ frame[1] =
+ 0x7f + (mask ? wsFrame.mask.TO_SERVER : wsFrame.mask.TO_CLIENT);
+ frame.writeUInt32BE(0, 2, true);
+ frame.writeUInt32BE(data.length, 6, true);
+ payloadOffset = 10;
+ }
+ //MASK
+ if (mask) {
+ mask.copy(frame, payloadOffset, 0, 4);
+ payloadOffset += 4;
+ }
+ //Payload
+ data.copy(frame, payloadOffset);
+ if (mask) {
+ wsFrame.applyMask(
+ frame.slice(payloadOffset),
+ frame.slice(payloadOffset - 4, payloadOffset),
+ );
+ }
+ return frame;
},
/**
@@ -127,7 +135,7 @@
* @property {Boolean} FIN - True is the message is complete
*/
- /** Decodes a WebSocket frame
+ /** Decodes a WebSocket frame
*
* @param {Buffer} frame - The raw inbound frame, if this is a continuation
* frame it must have a mask property with the mask.
@@ -135,54 +143,55 @@
*
* @see {@link WSDecodeResult}
*/
- decode: function(frame) {
- var result = {
- data: null,
- mask: null,
- binEncoding: false,
- nextFrame: null,
- FIN: true
- };
+ decode: function (frame) {
+ var result = {
+ data: null,
+ mask: null,
+ binEncoding: false,
+ nextFrame: null,
+ FIN: true,
+ };
- //Byte 0 - FIN & OPCODE
- if (wsFrame.fin.FIN != (frame[0] & wsFrame.fin.FIN)) {
- result.FIN = false;
- }
- result.binEncoding = (wsFrame.frameOpCodes.BIN == (frame[0] & wsFrame.frameOpCodes.BIN));
- //Byte 1 or 1-3 or 1-9 - SIZE
- var lenByte = (frame[1] & 0x0000007F);
- var len = lenByte;
- var dataOffset = 2;
- if (lenByte == 0x7E) {
- len = frame.readUInt16BE(2);
- dataOffset = 4;
- } else if (lenByte == 0x7F) {
- len = frame.readUInt32BE(6);
- dataOffset = 10;
- }
- //MASK
- if (wsFrame.mask.TO_SERVER == (frame[1] & wsFrame.mask.TO_SERVER)) {
- result.mask = new Buffer(4);
- frame.copy(result.mask, 0, dataOffset, dataOffset + 4);
- dataOffset += 4;
- }
- //Payload
- result.data = new Buffer(len);
- frame.copy(result.data, 0, dataOffset, dataOffset+len);
- if (result.mask) {
- wsFrame.applyMask(result.data, result.mask);
- }
- //Next Frame
- if (frame.length > dataOffset+len) {
- result.nextFrame = new Buffer(frame.length - (dataOffset+len));
- frame.copy(result.nextFrame, 0, dataOffset+len, frame.length);
- }
- //Don't forward control frames
- if (frame[0] & wsFrame.frameOpCodes.FINCTRL) {
- result.data = null;
- }
+ //Byte 0 - FIN & OPCODE
+ if (wsFrame.fin.FIN != (frame[0] & wsFrame.fin.FIN)) {
+ result.FIN = false;
+ }
+ result.binEncoding =
+ wsFrame.frameOpCodes.BIN == (frame[0] & wsFrame.frameOpCodes.BIN);
+ //Byte 1 or 1-3 or 1-9 - SIZE
+ var lenByte = frame[1] & 0x0000007f;
+ var len = lenByte;
+ var dataOffset = 2;
+ if (lenByte == 0x7e) {
+ len = frame.readUInt16BE(2);
+ dataOffset = 4;
+ } else if (lenByte == 0x7f) {
+ len = frame.readUInt32BE(6);
+ dataOffset = 10;
+ }
+ //MASK
+ if (wsFrame.mask.TO_SERVER == (frame[1] & wsFrame.mask.TO_SERVER)) {
+ result.mask = new Buffer(4);
+ frame.copy(result.mask, 0, dataOffset, dataOffset + 4);
+ dataOffset += 4;
+ }
+ //Payload
+ result.data = new Buffer(len);
+ frame.copy(result.data, 0, dataOffset, dataOffset + len);
+ if (result.mask) {
+ wsFrame.applyMask(result.data, result.mask);
+ }
+ //Next Frame
+ if (frame.length > dataOffset + len) {
+ result.nextFrame = new Buffer(frame.length - (dataOffset + len));
+ frame.copy(result.nextFrame, 0, dataOffset + len, frame.length);
+ }
+ //Don't forward control frames
+ if (frame[0] & wsFrame.frameOpCodes.FINCTRL) {
+ result.data = null;
+ }
- return result;
+ return result;
},
/** Masks/Unmasks data
@@ -190,12 +199,12 @@
* @param {Buffer} data - data to mask/unmask in place
* @param {Buffer} mask - the mask
*/
- applyMask: function(data, mask){
+ applyMask: function (data, mask) {
//TODO: look into xoring words at a time
var dataLen = data.length;
var maskLen = mask.length;
for (var i = 0; i < dataLen; i++) {
- data[i] = data[i] ^ mask[i%maskLen];
+ data[i] = data[i] ^ mask[i % maskLen];
}
},
@@ -204,35 +213,34 @@
* @param {Buffer} data - data.length is the assumed payload size
* @param {Boolean} mask - true if a mask will be sent (TO_SERVER)
*/
- frameSizeFromData: function(data, mask) {
+ frameSizeFromData: function (data, mask) {
var headerSize = 10;
- if (data.length < 0x7E) {
+ if (data.length < 0x7e) {
headerSize = 2;
- } else if (data.length < 0xFFFF) {
+ } else if (data.length < 0xffff) {
headerSize = 4;
}
return headerSize + data.length + (mask ? 4 : 0);
},
frameOpCodes: {
- CONT: 0x00,
- TEXT: 0x01,
- BIN: 0x02,
- CTRL: 0x80
+ CONT: 0x00,
+ TEXT: 0x01,
+ BIN: 0x02,
+ CTRL: 0x80,
},
mask: {
TO_SERVER: 0x80,
- TO_CLIENT: 0x00
+ TO_CLIENT: 0x00,
},
fin: {
CONT: 0x00,
- FIN: 0x80
- }
+ FIN: 0x80,
+ },
};
-
// createWebServer constructor and options
/////////////////////////////////////////////////////////////////////
@@ -272,20 +280,20 @@
* @param {ServerOptions} options - The server configuration.
* @returns {object} - The Apache Thrift Web Server.
*/
-exports.createWebServer = function(options) {
+exports.createWebServer = function (options) {
var baseDir = options.files;
var contentTypesByExtension = {
- '.txt': 'text/plain',
- '.html': 'text/html',
- '.css': 'text/css',
- '.xml': 'application/xml',
- '.json': 'application/json',
- '.js': 'application/javascript',
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.png': 'image/png',
- '.svg': 'image/svg+xml'
+ ".txt": "text/plain",
+ ".html": "text/html",
+ ".css": "text/css",
+ ".xml": "application/xml",
+ ".json": "application/json",
+ ".js": "application/javascript",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".png": "image/png",
+ ".svg": "image/svg+xml",
};
//Setup all of the services
@@ -302,8 +310,9 @@
// IDL Compiler generated class housing the processor. Also, the options property
// for a Processor has been called both cls and processor at different times. We
// support any of the four possibilities here.
- var processor = (svcObj.processor) ? (svcObj.processor.Processor || svcObj.processor) :
- (svcObj.cls.Processor || svcObj.cls);
+ var processor = svcObj.processor
+ ? svcObj.processor.Processor || svcObj.processor
+ : svcObj.cls.Processor || svcObj.cls;
//Processors can be supplied as constructed objects with handlers already embedded,
// if a handler is provided we construct a new processor, if not we use the processor
// object directly
@@ -322,9 +331,18 @@
if (request.headers.origin && options.cors) {
if (options.cors["*"] || options.cors[request.headers.origin]) {
//Allow, origin allowed
- response.setHeader("access-control-allow-origin", request.headers.origin);
- response.setHeader("access-control-allow-methods", "GET, POST, OPTIONS");
- response.setHeader("access-control-allow-headers", "content-type, accept");
+ response.setHeader(
+ "access-control-allow-origin",
+ request.headers.origin,
+ );
+ response.setHeader(
+ "access-control-allow-methods",
+ "GET, POST, OPTIONS",
+ );
+ response.setHeader(
+ "access-control-allow-headers",
+ "content-type, accept",
+ );
response.setHeader("access-control-max-age", "60");
return true;
} else {
@@ -336,19 +354,21 @@
return true;
}
-
//Handle OPTIONS method (CORS)
///////////////////////////////////////////////////
function processOptions(request, response) {
if (VerifyCORSAndSetHeaders(request, response)) {
- response.writeHead("204", "No Content", {"content-length": 0});
+ response.writeHead("204", "No Content", { "content-length": 0 });
} else {
- response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {});
+ response.writeHead(
+ "403",
+ "Origin " + request.headers.origin + " not allowed",
+ {},
+ );
}
response.end();
}
-
//Handle POST methods (TXHRTransport)
///////////////////////////////////////////////////
function processPost(request, response) {
@@ -363,39 +383,47 @@
//Verify CORS requirements
if (!VerifyCORSAndSetHeaders(request, response)) {
- response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {});
+ response.writeHead(
+ "403",
+ "Origin " + request.headers.origin + " not allowed",
+ {},
+ );
response.end();
return;
}
//Process XHR payload
- request.on('data', svc.transport.receiver(function(transportWithData) {
- var input = new svc.protocol(transportWithData);
- var output = new svc.protocol(new svc.transport(undefined, function(buf) {
+ request.on(
+ "data",
+ svc.transport.receiver(function (transportWithData) {
+ var input = new svc.protocol(transportWithData);
+ var output = new svc.protocol(
+ new svc.transport(undefined, function (buf) {
+ try {
+ response.writeHead(200);
+ response.end(buf);
+ } catch (err) {
+ response.writeHead(500);
+ response.end();
+ }
+ }),
+ );
+
try {
- response.writeHead(200);
- response.end(buf);
+ svc.processor.process(input, output);
+ transportWithData.commitPosition();
} catch (err) {
- response.writeHead(500);
- response.end();
+ if (err instanceof InputBufferUnderrunError) {
+ transportWithData.rollbackPosition();
+ } else {
+ response.writeHead(500);
+ response.end();
+ }
}
- }));
-
- try {
- svc.processor.process(input, output);
- transportWithData.commitPosition();
- } catch (err) {
- if (err instanceof InputBufferUnderrunError) {
- transportWithData.rollbackPosition();
- } else {
- response.writeHead(500);
- response.end();
- }
- }
- }));
+ }),
+ );
}
-
//Handle GET methods (Static Page Server)
///////////////////////////////////////////////////
function processGet(request, response) {
@@ -408,7 +436,11 @@
//Verify CORS requirements
if (!VerifyCORSAndSetHeaders(request, response)) {
- response.writeHead("403", "Origin " + request.headers.origin + " not allowed", {});
+ response.writeHead(
+ "403",
+ "Origin " + request.headers.origin + " not allowed",
+ {},
+ );
response.end();
return;
}
@@ -424,18 +456,18 @@
return;
}
- fs.exists(filename, function(exists) {
- if(!exists) {
+ fs.exists(filename, function (exists) {
+ if (!exists) {
response.writeHead(404);
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
- filename += '/index.html';
+ filename += "/index.html";
}
- fs.readFile(filename, "binary", function(err, file) {
+ fs.readFile(filename, "binary", function (err, file) {
if (err) {
response.writeHead(500);
response.end(err + "\n");
@@ -456,30 +488,29 @@
});
}
-
//Handle WebSocket calls (TWebSocketTransport)
///////////////////////////////////////////////////
function processWS(data, socket, svc, binEncoding) {
- svc.transport.receiver(function(transportWithData) {
+ svc.transport.receiver(function (transportWithData) {
var input = new svc.protocol(transportWithData);
- var output = new svc.protocol(new svc.transport(undefined, function(buf) {
- try {
- var frame = wsFrame.encode(buf, null, binEncoding);
- socket.write(frame);
- } catch (err) {
- //TODO: Add better error processing
- }
- }));
+ var output = new svc.protocol(
+ new svc.transport(undefined, function (buf) {
+ try {
+ var frame = wsFrame.encode(buf, null, binEncoding);
+ socket.write(frame);
+ } catch (err) {
+ //TODO: Add better error processing
+ }
+ }),
+ );
try {
svc.processor.process(input, output);
transportWithData.commitPosition();
- }
- catch (err) {
+ } catch (err) {
if (err instanceof InputBufferUnderrunError) {
transportWithData.rollbackPosition();
- }
- else {
+ } else {
//TODO: Add better error processing
}
}
@@ -498,69 +529,83 @@
// - GET static files,
// - POST XHR Thrift services
// - OPTIONS CORS requests
- server.on('request', function(request, response) {
- if (request.method === 'POST') {
- processPost(request, response);
- } else if (request.method === 'GET') {
- processGet(request, response);
- } else if (request.method === 'OPTIONS') {
- processOptions(request, response);
- } else {
- response.writeHead(500);
- response.end();
- }
- }).on('upgrade', function(request, socket, head) {
- //Lookup service
- var svc;
- try {
- svc = services[Object.keys(services)[0]];
- } catch(e) {
- socket.write("HTTP/1.1 403 No Apache Thrift Service available\r\n\r\n");
- return;
- }
- //Perform upgrade
- var hash = crypto.createHash("sha1");
- hash.update(request.headers['sec-websocket-key'] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
- socket.write("HTTP/1.1 101 Switching Protocols\r\n" +
- "Upgrade: websocket\r\n" +
- "Connection: Upgrade\r\n" +
- "Sec-WebSocket-Accept: " + hash.digest("base64") + "\r\n" +
- "Sec-WebSocket-Origin: " + request.headers.origin + "\r\n" +
- "Sec-WebSocket-Location: ws://" + request.headers.host + request.url + "\r\n" +
- "\r\n");
- //Handle WebSocket traffic
- var data = null;
- socket.on('data', function(frame) {
- try {
- while (frame) {
- var result = wsFrame.decode(frame);
- //Prepend any existing decoded data
- if (data) {
- if (result.data) {
- var newData = new Buffer(data.length + result.data.length);
- data.copy(newData);
- result.data.copy(newData, data.length);
- result.data = newData;
- } else {
- result.data = data;
- }
- data = null;
- }
- //If this completes a message process it
- if (result.FIN) {
- processWS(result.data, socket, svc, result.binEncoding);
- } else {
- data = result.data;
- }
- //Prepare next frame for decoding (if any)
- frame = result.nextFrame;
- }
- } catch(e) {
- log.error('TWebSocketTransport Exception: ' + e);
- socket.destroy();
+ server
+ .on("request", function (request, response) {
+ if (request.method === "POST") {
+ processPost(request, response);
+ } else if (request.method === "GET") {
+ processGet(request, response);
+ } else if (request.method === "OPTIONS") {
+ processOptions(request, response);
+ } else {
+ response.writeHead(500);
+ response.end();
}
+ })
+ .on("upgrade", function (request, socket, head) {
+ //Lookup service
+ var svc;
+ try {
+ svc = services[Object.keys(services)[0]];
+ } catch (e) {
+ socket.write("HTTP/1.1 403 No Apache Thrift Service available\r\n\r\n");
+ return;
+ }
+ //Perform upgrade
+ var hash = crypto.createHash("sha1");
+ hash.update(
+ request.headers["sec-websocket-key"] +
+ "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
+ );
+ socket.write(
+ "HTTP/1.1 101 Switching Protocols\r\n" +
+ "Upgrade: websocket\r\n" +
+ "Connection: Upgrade\r\n" +
+ "Sec-WebSocket-Accept: " +
+ hash.digest("base64") +
+ "\r\n" +
+ "Sec-WebSocket-Origin: " +
+ request.headers.origin +
+ "\r\n" +
+ "Sec-WebSocket-Location: ws://" +
+ request.headers.host +
+ request.url +
+ "\r\n" +
+ "\r\n",
+ );
+ //Handle WebSocket traffic
+ var data = null;
+ socket.on("data", function (frame) {
+ try {
+ while (frame) {
+ var result = wsFrame.decode(frame);
+ //Prepend any existing decoded data
+ if (data) {
+ if (result.data) {
+ var newData = new Buffer(data.length + result.data.length);
+ data.copy(newData);
+ result.data.copy(newData, data.length);
+ result.data = newData;
+ } else {
+ result.data = data;
+ }
+ data = null;
+ }
+ //If this completes a message process it
+ if (result.FIN) {
+ processWS(result.data, socket, svc, result.binEncoding);
+ } else {
+ data = result.data;
+ }
+ //Prepare next frame for decoding (if any)
+ frame = result.nextFrame;
+ }
+ } catch (e) {
+ log.error("TWebSocketTransport Exception: " + e);
+ socket.destroy();
+ }
+ });
});
- });
//Return the server
return server;
diff --git a/lib/nodejs/lib/thrift/ws_connection.js b/lib/nodejs/lib/thrift/ws_connection.js
index 8ee8f6e..878a572 100644
--- a/lib/nodejs/lib/thrift/ws_connection.js
+++ b/lib/nodejs/lib/thrift/ws_connection.js
@@ -16,17 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
-var WebSocket = require('isomorphic-ws');
+var util = require("util");
+var WebSocket = require("isomorphic-ws");
var EventEmitter = require("events").EventEmitter;
-var thrift = require('./thrift');
+var thrift = require("./thrift");
-var TBufferedTransport = require('./buffered_transport');
-var TJSONProtocol = require('./json_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TJSONProtocol = require("./json_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
-var createClient = require('./create_client');
-var jsEnv = require('browser-or-node');
+var createClient = require("./create_client");
+var jsEnv = require("browser-or-node");
exports.WSConnection = WSConnection;
/**
@@ -95,38 +95,38 @@
this.wsOptions = {
host: this.host,
port: this.port || 80,
- path: this.options.path || '/',
- headers: this.options.headers || {}
+ path: this.options.path || "/",
+ headers: this.options.headers || {},
};
for (var attrname in this.options.wsOptions) {
this.wsOptions[attrname] = this.options.wsOptions[attrname];
}
-};
+}
util.inherits(WSConnection, EventEmitter);
-WSConnection.prototype.__reset = function() {
+WSConnection.prototype.__reset = function () {
this.socket = null; //The web socket
this.send_pending = []; //Buffers/Callback pairs waiting to be sent
};
-WSConnection.prototype.__onOpen = function() {
+WSConnection.prototype.__onOpen = function () {
this.emit("open");
if (this.send_pending.length > 0) {
//If the user made calls before the connection was fully
//open, send them now
- this.send_pending.forEach(function(data) {
+ this.send_pending.forEach(function (data) {
this.socket.send(data);
}, this);
this.send_pending = [];
}
};
-WSConnection.prototype.__onClose = function(evt) {
+WSConnection.prototype.__onClose = function (evt) {
this.emit("close");
this.__reset();
};
-WSConnection.prototype.__decodeCallback = function(transport_with_data) {
+WSConnection.prototype.__decodeCallback = function (transport_with_data) {
var proto = new this.protocol(transport_with_data);
try {
while (true) {
@@ -151,7 +151,7 @@
delete this.seqId2Service[header.rseqid];
}
/*jshint -W083 */
- client._reqs[dummy_seqid] = function(err, success) {
+ client._reqs[dummy_seqid] = function (err, success) {
transport_with_data.commitPosition();
var clientCallback = client._reqs[header.rseqid];
delete client._reqs[header.rseqid];
@@ -160,14 +160,17 @@
}
};
/*jshint +W083 */
- if (client['recv_' + header.fname]) {
- client['recv_' + header.fname](proto, header.mtype, dummy_seqid);
+ if (client["recv_" + header.fname]) {
+ client["recv_" + header.fname](proto, header.mtype, dummy_seqid);
} else {
delete client._reqs[dummy_seqid];
- this.emit("error",
+ this.emit(
+ "error",
new thrift.TApplicationException(
thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
- "Received a response to an unknown RPC function"));
+ "Received a response to an unknown RPC function",
+ ),
+ );
}
}
} catch (e) {
@@ -179,20 +182,19 @@
}
};
-WSConnection.prototype.__onData = function(data) {
+WSConnection.prototype.__onData = function (data) {
if (Object.prototype.toString.call(data) === "[object ArrayBuffer]") {
data = new Uint8Array(data);
}
var buf = new Buffer(data);
this.transport.receiver(this.__decodeCallback.bind(this))(buf);
-
};
-WSConnection.prototype.__onMessage = function(evt) {
+WSConnection.prototype.__onMessage = function (evt) {
this.__onData(evt.data);
};
-WSConnection.prototype.__onError = function(evt) {
+WSConnection.prototype.__onError = function (evt) {
this.emit("error", evt);
this.socket.close();
};
@@ -202,14 +204,14 @@
* @readonly
* @returns {boolean}
*/
-WSConnection.prototype.isOpen = function() {
+WSConnection.prototype.isOpen = function () {
return this.socket && this.socket.readyState === this.socket.OPEN;
};
/**
* Opens the transport connection
*/
-WSConnection.prototype.open = function() {
+WSConnection.prototype.open = function () {
//If OPEN/CONNECTING/CLOSING ignore additional opens
if (this.socket && this.socket.readyState !== this.socket.CLOSED) {
return;
@@ -220,7 +222,7 @@
} else {
this.socket = new WebSocket(this.uri(), "", this.wsOptions);
}
- this.socket.binaryType = 'arraybuffer';
+ this.socket.binaryType = "arraybuffer";
this.socket.onopen = this.__onOpen.bind(this);
this.socket.onmessage = this.__onMessage.bind(this);
this.socket.onerror = this.__onError.bind(this);
@@ -230,7 +232,7 @@
/**
* Closes the transport connection
*/
-WSConnection.prototype.close = function() {
+WSConnection.prototype.close = function () {
this.socket.close();
};
@@ -238,19 +240,22 @@
* Return URI for the connection
* @returns {string} URI
*/
-WSConnection.prototype.uri = function() {
- var schema = this.secure ? 'wss' : 'ws';
- var port = '';
- var path = this.path || '/';
+WSConnection.prototype.uri = function () {
+ var schema = this.secure ? "wss" : "ws";
+ var port = "";
+ var path = this.path || "/";
var host = this.host;
// avoid port if default for schema
- if (this.port && (('wss' === schema && this.port !== 443) ||
- ('ws' === schema && this.port !== 80))) {
- port = ':' + this.port;
+ if (
+ this.port &&
+ (("wss" === schema && this.port !== 443) ||
+ ("ws" === schema && this.port !== 80))
+ ) {
+ port = ":" + this.port;
}
- return schema + '://' + host + port + path;
+ return schema + "://" + host + port + path;
};
/**
@@ -260,7 +265,7 @@
* @event {error} the "error" event is raised upon request failure passing the
* Node.js error object to the listener.
*/
-WSConnection.prototype.write = function(data) {
+WSConnection.prototype.write = function (data) {
if (this.isOpen()) {
//Send data and register a callback to invoke the client callback
this.socket.send(data);
@@ -279,7 +284,7 @@
* @returns {WSConnection} The connection object.
* @see {@link WSConnectOptions}
*/
-exports.createWSConnection = function(host, port, options) {
+exports.createWSConnection = function (host, port, options) {
return new WSConnection(host, port, options);
};
diff --git a/lib/nodejs/lib/thrift/ws_transport.js b/lib/nodejs/lib/thrift/ws_transport.js
index 4cf62b9..94b6d90 100644
--- a/lib/nodejs/lib/thrift/ws_transport.js
+++ b/lib/nodejs/lib/thrift/ws_transport.js
@@ -17,7 +17,7 @@
* under the License.
*/
-var log = require('./log');
+var log = require("./log");
module.exports = TWebSocketTransport;
@@ -33,19 +33,18 @@
* var transport = new Thrift.TWebSocketTransport("http://localhost:8585");
*/
function TWebSocketTransport(url) {
- this.__reset(url);
-};
+ this.__reset(url);
+}
-
-TWebSocketTransport.prototype.__reset = function(url) {
- this.url = url; //Where to connect
- this.socket = null; //The web socket
- this.callbacks = []; //Pending callbacks
- this.send_pending = []; //Buffers/Callback pairs waiting to be sent
- this.send_buf = ''; //Outbound data, immutable until sent
- this.recv_buf = ''; //Inbound data
- this.rb_wpos = 0; //Network write position in receive buffer
- this.rb_rpos = 0; //Client read position in receive buffer
+TWebSocketTransport.prototype.__reset = function (url) {
+ this.url = url; //Where to connect
+ this.socket = null; //The web socket
+ this.callbacks = []; //Pending callbacks
+ this.send_pending = []; //Buffers/Callback pairs waiting to be sent
+ this.send_buf = ""; //Outbound data, immutable until sent
+ this.recv_buf = ""; //Inbound data
+ this.rb_wpos = 0; //Network write position in receive buffer
+ this.rb_rpos = 0; //Client read position in receive buffer
};
/**
@@ -56,58 +55,62 @@
* @param {object} callback - The client completion callback.
* @returns {undefined|string} Nothing (undefined)
*/
-TWebSocketTransport.prototype.flush = function(async, callback) {
+TWebSocketTransport.prototype.flush = function (async, callback) {
var self = this;
if (this.isOpen()) {
//Send data and register a callback to invoke the client callback
this.socket.send(this.send_buf);
- this.callbacks.push((function() {
- var clientCallback = callback;
- return function(msg) {
- self.setRecvBuffer(msg);
- clientCallback();
- };
- }()));
+ this.callbacks.push(
+ (function () {
+ var clientCallback = callback;
+ return function (msg) {
+ self.setRecvBuffer(msg);
+ clientCallback();
+ };
+ })(),
+ );
} else {
//Queue the send to go out __onOpen
this.send_pending.push({
buf: this.send_buf,
- cb: callback
+ cb: callback,
});
}
};
-TWebSocketTransport.prototype.__onOpen = function() {
- var self = this;
- if (this.send_pending.length > 0) {
- //If the user made calls before the connection was fully
- //open, send them now
- this.send_pending.forEach(function(elem) {
- self.socket.send(elem.buf);
- self.callbacks.push((function() {
- var clientCallback = elem.cb;
- return function(msg) {
- self.setRecvBuffer(msg);
- clientCallback();
- };
- }()));
- });
- this.send_pending = [];
- }
+TWebSocketTransport.prototype.__onOpen = function () {
+ var self = this;
+ if (this.send_pending.length > 0) {
+ //If the user made calls before the connection was fully
+ //open, send them now
+ this.send_pending.forEach(function (elem) {
+ self.socket.send(elem.buf);
+ self.callbacks.push(
+ (function () {
+ var clientCallback = elem.cb;
+ return function (msg) {
+ self.setRecvBuffer(msg);
+ clientCallback();
+ };
+ })(),
+ );
+ });
+ this.send_pending = [];
+ }
};
-TWebSocketTransport.prototype.__onClose = function(evt) {
+TWebSocketTransport.prototype.__onClose = function (evt) {
this.__reset(this.url);
};
-TWebSocketTransport.prototype.__onMessage = function(evt) {
+TWebSocketTransport.prototype.__onMessage = function (evt) {
if (this.callbacks.length) {
this.callbacks.shift()(evt.data);
}
};
-TWebSocketTransport.prototype.__onError = function(evt) {
- log.error('websocket: ' + evt.toString());
+TWebSocketTransport.prototype.__onError = function (evt) {
+ log.error("websocket: " + evt.toString());
this.socket.close();
};
@@ -115,7 +118,7 @@
* Sets the buffer to use when receiving server responses.
* @param {string} buf - The buffer to receive server responses.
*/
-TWebSocketTransport.prototype.setRecvBuffer = function(buf) {
+TWebSocketTransport.prototype.setRecvBuffer = function (buf) {
this.recv_buf = buf;
this.recv_buf_sz = this.recv_buf.length;
this.wpos = this.recv_buf.length;
@@ -127,14 +130,14 @@
* @readonly
* @returns {boolean}
*/
-TWebSocketTransport.prototype.isOpen = function() {
+TWebSocketTransport.prototype.isOpen = function () {
return this.socket && this.socket.readyState == this.socket.OPEN;
};
/**
* Opens the transport connection
*/
-TWebSocketTransport.prototype.open = function() {
+TWebSocketTransport.prototype.open = function () {
//If OPEN/CONNECTING/CLOSING ignore additional opens
if (this.socket && this.socket.readyState != this.socket.CLOSED) {
return;
@@ -150,7 +153,7 @@
/**
* Closes the transport connection
*/
-TWebSocketTransport.prototype.close = function() {
+TWebSocketTransport.prototype.close = function () {
this.socket.close();
};
@@ -160,11 +163,11 @@
* @param {number} len - The number of characters to return.
* @returns {string} Characters sent by the server.
*/
-TWebSocketTransport.prototype.read = function(len) {
+TWebSocketTransport.prototype.read = function (len) {
var avail = this.wpos - this.rpos;
if (avail === 0) {
- return '';
+ return "";
}
var give = len;
@@ -184,7 +187,7 @@
* Returns the entire response buffer.
* @returns {string} Characters sent by the server.
*/
-TWebSocketTransport.prototype.readAll = function() {
+TWebSocketTransport.prototype.readAll = function () {
return this.recv_buf;
};
@@ -192,7 +195,7 @@
* Sets the send buffer to buf.
* @param {string} buf - The buffer to send.
*/
-TWebSocketTransport.prototype.write = function(buf) {
+TWebSocketTransport.prototype.write = function (buf) {
this.send_buf = buf;
};
@@ -201,6 +204,6 @@
* @readonly
* @returns {string} The send buffer.
*/
-TWebSocketTransport.prototype.getSendBuffer = function() {
+TWebSocketTransport.prototype.getSendBuffer = function () {
return this.send_buf;
};
diff --git a/lib/nodejs/lib/thrift/xhr_connection.js b/lib/nodejs/lib/thrift/xhr_connection.js
index 6459c90..ea542d1 100644
--- a/lib/nodejs/lib/thrift/xhr_connection.js
+++ b/lib/nodejs/lib/thrift/xhr_connection.js
@@ -16,15 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
-var util = require('util');
+var util = require("util");
var EventEmitter = require("events").EventEmitter;
-var thrift = require('./thrift');
+var thrift = require("./thrift");
-var TBufferedTransport = require('./buffered_transport');
-var TJSONProtocol = require('./json_protocol');
-var InputBufferUnderrunError = require('./input_buffer_underrun_error');
+var TBufferedTransport = require("./buffered_transport");
+var TJSONProtocol = require("./json_protocol");
+var InputBufferUnderrunError = require("./input_buffer_underrun_error");
-var createClient = require('./create_client');
+var createClient = require("./create_client");
exports.XHRConnection = XHRConnection;
@@ -43,43 +43,49 @@
this.options = options || {};
this.wpos = 0;
this.rpos = 0;
- this.useCORS = (options && options.useCORS);
- this.send_buf = '';
- this.recv_buf = '';
+ this.useCORS = options && options.useCORS;
+ this.send_buf = "";
+ this.recv_buf = "";
this.transport = options.transport || TBufferedTransport;
this.protocol = options.protocol || TJSONProtocol;
this.headers = options.headers || {};
host = host || window.location.host;
port = port || window.location.port;
- var prefix = options.https ? 'https://' : 'http://';
- var path = options.path || '/';
+ var prefix = options.https ? "https://" : "http://";
+ var path = options.path || "/";
- if (port === '') {
+ if (port === "") {
port = undefined;
}
- if (!port || port === 80 || port === '80') {
+ if (!port || port === 80 || port === "80") {
this.url = prefix + host + path;
} else {
- this.url = prefix + host + ':' + port + path;
+ this.url = prefix + host + ":" + port + path;
}
//The sequence map is used to map seqIDs back to the
// calling client in multiplexed scenarios
this.seqId2Service = {};
-};
+}
util.inherits(XHRConnection, EventEmitter);
/**
-* Gets the browser specific XmlHttpRequest Object.
-* @returns {object} the browser XHR interface object
-*/
-XHRConnection.prototype.getXmlHttpRequestObject = function() {
- try { return new XMLHttpRequest(); } catch (e1) { }
- try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e2) { }
- try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e3) { }
+ * Gets the browser specific XmlHttpRequest Object.
+ * @returns {object} the browser XHR interface object
+ */
+XHRConnection.prototype.getXmlHttpRequestObject = function () {
+ try {
+ return new XMLHttpRequest();
+ } catch (e1) {}
+ try {
+ return new ActiveXObject("Msxml2.XMLHTTP");
+ } catch (e2) {}
+ try {
+ return new ActiveXObject("Microsoft.XMLHTTP");
+ } catch (e3) {}
throw "Your browser doesn't support XHR.";
};
@@ -94,27 +100,27 @@
* @returns {undefined|string} Nothing or the current send buffer.
* @throws {string} If XHR fails.
*/
-XHRConnection.prototype.flush = function() {
+XHRConnection.prototype.flush = function () {
var self = this;
- if (this.url === undefined || this.url === '') {
+ if (this.url === undefined || this.url === "") {
return this.send_buf;
}
var xreq = this.getXmlHttpRequestObject();
if (xreq.overrideMimeType) {
- xreq.overrideMimeType('application/json');
+ xreq.overrideMimeType("application/json");
}
- xreq.onreadystatechange = function() {
+ xreq.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
self.setRecvBuffer(this.responseText);
}
};
- xreq.open('POST', this.url, true);
+ xreq.open("POST", this.url, true);
- Object.keys(this.headers).forEach(function(headerKey) {
+ Object.keys(this.headers).forEach(function (headerKey) {
xreq.setRequestHeader(headerKey, self.headers[headerKey]);
});
@@ -125,7 +131,7 @@
* Sets the buffer to provide the protocol when deserializing.
* @param {string} buf - The buffer to supply the protocol.
*/
-XHRConnection.prototype.setRecvBuffer = function(buf) {
+XHRConnection.prototype.setRecvBuffer = function (buf) {
this.recv_buf = buf;
this.recv_buf_sz = this.recv_buf.length;
this.wpos = this.recv_buf.length;
@@ -137,10 +143,9 @@
var thing = new Buffer(data || buf);
this.transport.receiver(this.__decodeCallback.bind(this))(thing);
-
};
-XHRConnection.prototype.__decodeCallback = function(transport_with_data) {
+XHRConnection.prototype.__decodeCallback = function (transport_with_data) {
var proto = new this.protocol(transport_with_data);
try {
while (true) {
@@ -165,7 +170,7 @@
delete this.seqId2Service[header.rseqid];
}
/*jshint -W083 */
- client._reqs[dummy_seqid] = function(err, success) {
+ client._reqs[dummy_seqid] = function (err, success) {
transport_with_data.commitPosition();
var clientCallback = client._reqs[header.rseqid];
delete client._reqs[header.rseqid];
@@ -174,14 +179,17 @@
}
};
/*jshint +W083 */
- if (client['recv_' + header.fname]) {
- client['recv_' + header.fname](proto, header.mtype, dummy_seqid);
+ if (client["recv_" + header.fname]) {
+ client["recv_" + header.fname](proto, header.mtype, dummy_seqid);
} else {
delete client._reqs[dummy_seqid];
- this.emit("error",
+ this.emit(
+ "error",
new thrift.TApplicationException(
thrift.TApplicationExceptionType.WRONG_METHOD_NAME,
- "Received a response to an unknown RPC function"));
+ "Received a response to an unknown RPC function",
+ ),
+ );
}
}
} catch (e) {
@@ -198,19 +206,19 @@
* @readonly
* @returns {boolean} Always True.
*/
-XHRConnection.prototype.isOpen = function() {
+XHRConnection.prototype.isOpen = function () {
return true;
};
/**
* Opens the transport connection, with XHR this is a nop.
*/
-XHRConnection.prototype.open = function() {};
+XHRConnection.prototype.open = function () {};
/**
* Closes the transport connection, with XHR this is a nop.
*/
-XHRConnection.prototype.close = function() {};
+XHRConnection.prototype.close = function () {};
/**
* Returns the specified number of characters from the response
@@ -218,11 +226,11 @@
* @param {number} len - The number of characters to return.
* @returns {string} Characters sent by the server.
*/
-XHRConnection.prototype.read = function(len) {
+XHRConnection.prototype.read = function (len) {
var avail = this.wpos - this.rpos;
if (avail === 0) {
- return '';
+ return "";
}
var give = len;
@@ -242,7 +250,7 @@
* Returns the entire response buffer.
* @returns {string} Characters sent by the server.
*/
-XHRConnection.prototype.readAll = function() {
+XHRConnection.prototype.readAll = function () {
return this.recv_buf;
};
@@ -250,7 +258,7 @@
* Sets the send buffer to buf.
* @param {string} buf - The buffer to send.
*/
-XHRConnection.prototype.write = function(buf) {
+XHRConnection.prototype.write = function (buf) {
this.send_buf = buf;
this.flush();
};
@@ -260,7 +268,7 @@
* @readonly
* @returns {string} The send buffer.
*/
-XHRConnection.prototype.getSendBuffer = function() {
+XHRConnection.prototype.getSendBuffer = function () {
return this.send_buf;
};
@@ -273,7 +281,7 @@
* @returns {XHRConnection} The connection object.
* @see {@link XHRConnectOptions}
*/
-exports.createXHRConnection = function(host, port, options) {
+exports.createXHRConnection = function (host, port, options) {
return new XHRConnection(host, port, options);
};
diff --git a/lib/nodejs/test/binary.test.js b/lib/nodejs/test/binary.test.js
index 187cd18..343d39a 100644
--- a/lib/nodejs/test/binary.test.js
+++ b/lib/nodejs/test/binary.test.js
@@ -21,7 +21,7 @@
const binary = require("thrift/binary");
const cases = {
- "Should read signed byte": function(assert) {
+ "Should read signed byte": function (assert) {
assert.equal(1, binary.readByte(0x01));
assert.equal(-1, binary.readByte(0xff));
@@ -29,12 +29,12 @@
assert.equal(-128, binary.readByte(0x80));
assert.end();
},
- "Should write byte": function(assert) {
+ "Should write byte": function (assert) {
//Protocol simply writes to the buffer. Nothing to test.. yet.
assert.ok(true);
assert.end();
},
- "Should read I16": function(assert) {
+ "Should read I16": function (assert) {
assert.equal(0, binary.readI16([0x00, 0x00]));
assert.equal(1, binary.readI16([0x00, 0x01]));
assert.equal(-1, binary.readI16([0xff, 0xff]));
@@ -46,7 +46,7 @@
assert.end();
},
- "Should write I16": function(assert) {
+ "Should write I16": function (assert) {
assert.deepEqual([0x00, 0x00], binary.writeI16([], 0));
assert.deepEqual([0x00, 0x01], binary.writeI16([], 1));
assert.deepEqual([0xff, 0xff], binary.writeI16([], -1));
@@ -58,7 +58,7 @@
assert.end();
},
- "Should read I32": function(assert) {
+ "Should read I32": function (assert) {
assert.equal(0, binary.readI32([0x00, 0x00, 0x00, 0x00]));
assert.equal(1, binary.readI32([0x00, 0x00, 0x00, 0x01]));
assert.equal(-1, binary.readI32([0xff, 0xff, 0xff, 0xff]));
@@ -70,7 +70,7 @@
assert.end();
},
- "Should write I32": function(assert) {
+ "Should write I32": function (assert) {
assert.deepEqual([0x00, 0x00, 0x00, 0x00], binary.writeI32([], 0));
assert.deepEqual([0x00, 0x00, 0x00, 0x01], binary.writeI32([], 1));
assert.deepEqual([0xff, 0xff, 0xff, 0xff], binary.writeI32([], -1));
@@ -78,137 +78,139 @@
// Min I32
assert.deepEqual(
[0x80, 0x00, 0x00, 0x00],
- binary.writeI32([], -2147483648)
+ binary.writeI32([], -2147483648),
);
// Max I32
assert.deepEqual([0x7f, 0xff, 0xff, 0xff], binary.writeI32([], 2147483647));
assert.end();
},
- "Should read doubles": function(assert) {
+ "Should read doubles": function (assert) {
assert.equal(
0,
- binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
0,
- binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
1,
- binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
2,
- binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
-2,
- binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
Math.PI,
- binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18])
+ binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]),
);
assert.equal(
Infinity,
- binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.equal(
-Infinity,
- binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
assert.ok(
- isNaN(binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
+ isNaN(
+ binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
+ ),
);
assert.equal(
1 / 3,
- binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55])
+ binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]),
);
// Min subnormal positive double
assert.equal(
4.9406564584124654e-324,
- binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])
+ binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]),
);
// Min normal positive double
assert.equal(
2.2250738585072014e-308,
- binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
+ binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
);
// Max positive double
assert.equal(
1.7976931348623157e308,
- binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])
+ binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
);
assert.end();
},
- "Should write doubles": function(assert) {
+ "Should write doubles": function (assert) {
assert.deepEqual(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], 0)
+ binary.writeDouble([], 0),
);
assert.deepEqual(
[0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], 1)
+ binary.writeDouble([], 1),
);
assert.deepEqual(
[0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], 2)
+ binary.writeDouble([], 2),
);
assert.deepEqual(
[0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], -2)
+ binary.writeDouble([], -2),
);
assert.deepEqual(
[0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18],
- binary.writeDouble([], Math.PI)
+ binary.writeDouble([], Math.PI),
);
assert.deepEqual(
[0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], Infinity)
+ binary.writeDouble([], Infinity),
);
assert.deepEqual(
[0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], -Infinity)
+ binary.writeDouble([], -Infinity),
);
assert.deepEqual(
[0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], NaN)
+ binary.writeDouble([], NaN),
);
assert.deepEqual(
[0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55],
- binary.writeDouble([], 1 / 3)
+ binary.writeDouble([], 1 / 3),
);
// Min subnormal positive double
assert.deepEqual(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
- binary.writeDouble([], 4.9406564584124654e-324)
+ binary.writeDouble([], 4.9406564584124654e-324),
);
// Min normal positive double
assert.deepEqual(
[0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
- binary.writeDouble([], 2.2250738585072014e-308)
+ binary.writeDouble([], 2.2250738585072014e-308),
);
// Max positive double
assert.deepEqual(
[0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
- binary.writeDouble([], 1.7976931348623157e308)
+ binary.writeDouble([], 1.7976931348623157e308),
);
assert.end();
- }
+ },
};
-Object.keys(cases).forEach(function(caseName) {
+Object.keys(cases).forEach(function (caseName) {
test(caseName, cases[caseName]);
});
diff --git a/lib/nodejs/test/client.js b/lib/nodejs/test/client.js
index 31ea06e..1d137ff 100644
--- a/lib/nodejs/test/client.js
+++ b/lib/nodejs/test/client.js
@@ -25,8 +25,8 @@
const ThriftTest = require(`./${helpers.genPath}/ThriftTest`);
const ThriftTestDriver = require("./test_driver").ThriftTestDriver;
-const ThriftTestDriverPromise = require("./test_driver")
- .ThriftTestDriverPromise;
+const ThriftTestDriverPromise =
+ require("./test_driver").ThriftTestDriverPromise;
const SecondService = require(`./${helpers.genPath}/SecondService`);
const program = require("commander");
@@ -34,24 +34,24 @@
program
.option(
"-p, --protocol <protocol>",
- "Set thrift protocol (binary|compact|json) [protocol]"
+ "Set thrift protocol (binary|compact|json) [protocol]",
)
.option(
"-t, --transport <transport>",
- "Set thrift transport (buffered|framed|http) [transport]"
+ "Set thrift transport (buffered|framed|http) [transport]",
)
.option("--port <port>", "Set thrift server port number to connect", 9090)
.option("--host <host>", "Set thrift server host to connect", "localhost")
.option(
"--domain-socket <path>",
- "Set thrift server unix domain socket to connect"
+ "Set thrift server unix domain socket to connect",
)
.option("--ssl", "use SSL transport")
.option("--callback", "test with callback style functions")
.option(
"-t, --type <type>",
"Select server type (http|multiplex|tcp|websocket)",
- "tcp"
+ "tcp",
)
.option("--es6", "Use es6 code")
.option("--es5", "Use es5 code")
@@ -76,7 +76,7 @@
const options = {
transport: helpers.transports[program.transport],
- protocol: helpers.protocols[program.protocol]
+ protocol: helpers.protocols[program.protocol],
};
if (type === "http" || type === "websocket") {
@@ -128,7 +128,7 @@
connection.open();
}
-connection.on("error", function(err) {
+connection.on("error", function (err) {
assert(false, err);
});
@@ -141,11 +141,11 @@
const secondclient = mp.createClient(
"SecondService",
SecondService,
- connection
+ connection,
);
- connection.on("connect", function() {
- secondclient.secondtestString("Test", function(err, response) {
+ connection.on("connect", function () {
+ secondclient.secondtestString("Test", function (err, response) {
assert(!err);
assert.equal('testString("Test")', response);
});
@@ -161,7 +161,7 @@
}
function runTests() {
- testDriver(client, function(status) {
+ testDriver(client, function (status) {
console.log(status);
if (type !== "http" && type !== "websocket") {
connection.end();
@@ -172,4 +172,4 @@
});
}
-exports.expressoTest = function() {};
+exports.expressoTest = function () {};
diff --git a/lib/nodejs/test/deep-constructor.test.js b/lib/nodejs/test/deep-constructor.test.js
index a91ddb1..e5ac3f8 100644
--- a/lib/nodejs/test/deep-constructor.test.js
+++ b/lib/nodejs/test/deep-constructor.test.js
@@ -24,7 +24,7 @@
function serializeBinary(data) {
let buff;
- const transport = new thrift.TBufferedTransport(null, function(msg) {
+ const transport = new thrift.TBufferedTransport(null, function (msg) {
buff = msg;
});
const prot = new thrift.TBinaryProtocol(transport);
@@ -43,7 +43,7 @@
function serializeJSON(data) {
let buff;
- const transport = new thrift.TBufferedTransport(null, function(msg) {
+ const transport = new thrift.TBufferedTransport(null, function (msg) {
buff = msg;
});
const protocol = new thrift.TJSONProtocol(transport);
@@ -70,17 +70,17 @@
struct_list_field: [
new ttypes.Simple({ value: "b" }),
- new ttypes.Simple({ value: "c" })
+ new ttypes.Simple({ value: "c" }),
],
struct_set_field: [
new ttypes.Simple({ value: "d" }),
- new ttypes.Simple({ value: "e" })
+ new ttypes.Simple({ value: "e" }),
],
struct_map_field: {
A: new ttypes.Simple({ value: "f" }),
- B: new ttypes.Simple({ value: "g" })
+ B: new ttypes.Simple({ value: "g" }),
},
struct_nested_containers_field: [
@@ -88,46 +88,46 @@
{
C: [
new ttypes.Simple({ value: "h" }),
- new ttypes.Simple({ value: "i" })
- ]
- }
- ]
+ new ttypes.Simple({ value: "i" }),
+ ],
+ },
+ ],
],
struct_nested_containers_field2: {
D: [
{
- DA: new ttypes.Simple({ value: "j" })
+ DA: new ttypes.Simple({ value: "j" }),
},
{
- DB: new ttypes.Simple({ value: "k" })
- }
- ]
+ DB: new ttypes.Simple({ value: "k" }),
+ },
+ ],
},
list_of_list_field: [
["l00", "l01", "l02"],
["l10", "l11", "l12"],
- ["l20", "l21", "l22"]
+ ["l20", "l21", "l22"],
],
list_of_list_of_list_field: [
[
["m000", "m001", "m002"],
["m010", "m011", "m012"],
- ["m020", "m021", "m022"]
+ ["m020", "m021", "m022"],
],
[
["m100", "m101", "m102"],
["m110", "m111", "m112"],
- ["m120", "m121", "m122"]
+ ["m120", "m121", "m122"],
],
[
["m200", "m201", "m202"],
["m210", "m211", "m212"],
- ["m220", "m221", "m222"]
- ]
- ]
+ ["m220", "m221", "m222"],
+ ],
+ ],
});
}
@@ -141,51 +141,51 @@
struct_map_field: {
A: { value: "f" },
- B: { value: "g" }
+ B: { value: "g" },
},
struct_nested_containers_field: [
[
{
- C: [{ value: "h" }, { value: "i" }]
- }
- ]
+ C: [{ value: "h" }, { value: "i" }],
+ },
+ ],
],
struct_nested_containers_field2: {
D: [
{
- DA: { value: "j" }
+ DA: { value: "j" },
},
{
- DB: { value: "k" }
- }
- ]
+ DB: { value: "k" },
+ },
+ ],
},
list_of_list_field: [
["l00", "l01", "l02"],
["l10", "l11", "l12"],
- ["l20", "l21", "l22"]
+ ["l20", "l21", "l22"],
],
list_of_list_of_list_field: [
[
["m000", "m001", "m002"],
["m010", "m011", "m012"],
- ["m020", "m021", "m022"]
+ ["m020", "m021", "m022"],
],
[
["m100", "m101", "m102"],
["m110", "m111", "m112"],
- ["m120", "m121", "m122"]
+ ["m120", "m121", "m122"],
],
[
["m200", "m201", "m202"],
["m210", "m211", "m212"],
- ["m220", "m221", "m222"]
- ]
- ]
+ ["m220", "m221", "m222"],
+ ],
+ ],
};
}
@@ -244,7 +244,7 @@
function createTestCases(serialize, deserialize) {
const cases = {
- "Serialize/deserialize should return equal object": function(assert) {
+ "Serialize/deserialize should return equal object": function (assert) {
const tObj = createThriftObj();
const received = deserialize(serialize(tObj), ttypes.Complex);
assert.ok(tObj !== received, "not the same object");
@@ -252,51 +252,49 @@
assert.end();
},
- "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects": function(
- assert
- ) {
- const tObj1 = createThriftObj();
- const tObj2 = new ttypes.Complex(createJsObj());
- assertValues(tObj2, assert);
- const s1 = serialize(tObj1);
- const s2 = serialize(tObj2);
- assert.ok(bufferEquals(s1, s2));
- assert.end();
- },
+ "Nested structs and containers initialized from plain js objects should serialize same as if initialized from thrift objects":
+ function (assert) {
+ const tObj1 = createThriftObj();
+ const tObj2 = new ttypes.Complex(createJsObj());
+ assertValues(tObj2, assert);
+ const s1 = serialize(tObj1);
+ const s2 = serialize(tObj2);
+ assert.ok(bufferEquals(s1, s2));
+ assert.end();
+ },
- "Modifications to args object should not affect constructed Thrift object": function(
- assert
- ) {
- const args = createJsObj();
- assertValues(args, assert);
+ "Modifications to args object should not affect constructed Thrift object":
+ function (assert) {
+ const args = createJsObj();
+ assertValues(args, assert);
- const tObj = new ttypes.Complex(args);
- assertValues(tObj, assert);
+ const tObj = new ttypes.Complex(args);
+ assertValues(tObj, assert);
- args.struct_field.value = "ZZZ";
- args.struct_list_field[0].value = "ZZZ";
- args.struct_list_field[1].value = "ZZZ";
- args.struct_set_field[0].value = "ZZZ";
- args.struct_set_field[1].value = "ZZZ";
- args.struct_map_field.A.value = "ZZZ";
- args.struct_map_field.B.value = "ZZZ";
- args.struct_nested_containers_field[0][0].C[0] = "ZZZ";
- args.struct_nested_containers_field[0][0].C[1] = "ZZZ";
- args.struct_nested_containers_field2.D[0].DA = "ZZZ";
- args.struct_nested_containers_field2.D[0].DB = "ZZZ";
+ args.struct_field.value = "ZZZ";
+ args.struct_list_field[0].value = "ZZZ";
+ args.struct_list_field[1].value = "ZZZ";
+ args.struct_set_field[0].value = "ZZZ";
+ args.struct_set_field[1].value = "ZZZ";
+ args.struct_map_field.A.value = "ZZZ";
+ args.struct_map_field.B.value = "ZZZ";
+ args.struct_nested_containers_field[0][0].C[0] = "ZZZ";
+ args.struct_nested_containers_field[0][0].C[1] = "ZZZ";
+ args.struct_nested_containers_field2.D[0].DA = "ZZZ";
+ args.struct_nested_containers_field2.D[0].DB = "ZZZ";
- assertValues(tObj, assert);
- assert.end();
- },
+ assertValues(tObj, assert);
+ assert.end();
+ },
- "nulls are ok": function(assert) {
+ "nulls are ok": function (assert) {
const tObj = new ttypes.Complex({
struct_field: null,
struct_list_field: null,
struct_set_field: null,
struct_map_field: null,
struct_nested_containers_field: null,
- struct_nested_containers_field2: null
+ struct_nested_containers_field2: null,
});
const received = deserialize(serialize(tObj), ttypes.Complex);
assert.strictEqual(tObj.struct_field, null);
@@ -305,9 +303,9 @@
assert.end();
},
- "Can make list with objects": function(assert) {
+ "Can make list with objects": function (assert) {
const tObj = new ttypes.ComplexList({
- struct_list_field: [new ttypes.Complex({})]
+ struct_list_field: [new ttypes.Complex({})],
});
const innerObj = tObj.struct_list_field[0];
assert.ok(innerObj instanceof ttypes.Complex);
@@ -318,13 +316,13 @@
assert.strictEqual(innerObj.struct_nested_containers_field, null);
assert.strictEqual(innerObj.struct_nested_containers_field2, null);
assert.end();
- }
+ },
};
return cases;
}
function run(name, cases) {
- Object.keys(cases).forEach(function(caseName) {
+ Object.keys(cases).forEach(function (caseName) {
test(name + ": " + caseName, cases[caseName]);
});
}
diff --git a/lib/nodejs/test/episodic-code-generation-test/client.js b/lib/nodejs/test/episodic-code-generation-test/client.js
index 55dc702..631bfe7 100644
--- a/lib/nodejs/test/episodic-code-generation-test/client.js
+++ b/lib/nodejs/test/episodic-code-generation-test/client.js
@@ -37,21 +37,21 @@
const options = {
transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol
+ protocol: thrift.TJSONProtocol,
};
const connection = thrift.createConnection(host, port, options);
-const testDriver = function(client, callback) {
- test("NodeJS episodic compilation client-server test", function(assert) {
+const testDriver = function (client, callback) {
+ test("NodeJS episodic compilation client-server test", function (assert) {
const type1Object = new Types.Type1();
type1Object.number = 42;
type1Object.message = "The answer";
- client.testEpisode(type1Object, function(err, response) {
+ client.testEpisode(type1Object, function (err, response) {
assert.error(err, "no callback error");
assert.equal(response.number, type1Object.number + 1);
assert.equal(
response.message,
- type1Object.message + " [Hello from the server]"
+ type1Object.message + " [Hello from the server]",
);
assert.end();
callback("Server successfully tested");
@@ -59,7 +59,7 @@
});
};
-connection.on("error", function(err) {
+connection.on("error", function (err) {
assert(false, err);
});
@@ -68,10 +68,10 @@
runTests();
function runTests() {
- testDriver(client, function(status) {
+ testDriver(client, function (status) {
console.log(status);
connection.destroy();
});
}
-exports.expressoTest = function() {};
+exports.expressoTest = function () {};
diff --git a/lib/nodejs/test/episodic-code-generation-test/server.js b/lib/nodejs/test/episodic-code-generation-test/server.js
index 2917b68..feca380 100644
--- a/lib/nodejs/test/episodic-code-generation-test/server.js
+++ b/lib/nodejs/test/episodic-code-generation-test/server.js
@@ -33,17 +33,17 @@
const options = {
transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol
+ protocol: thrift.TJSONProtocol,
};
const ServiceHandler = {
- testEpisode: function(receivedType1Object) {
+ testEpisode: function (receivedType1Object) {
const type1Object = new Types.Type1();
type1Object.number = receivedType1Object.number + 1;
type1Object.message =
receivedType1Object.message + " [Hello from the server]";
return type1Object;
- }
+ },
};
const server = thrift.createServer(Service, ServiceHandler, options);
diff --git a/lib/nodejs/test/exceptions.js b/lib/nodejs/test/exceptions.js
index f30f987..4119e76 100644
--- a/lib/nodejs/test/exceptions.js
+++ b/lib/nodejs/test/exceptions.js
@@ -26,23 +26,23 @@
const e = new thrift.TApplicationException(1, "foo");
assert.ok(
e instanceof thrift.TApplicationException,
- "is instanceof TApplicationException"
+ "is instanceof TApplicationException",
);
assert.ok(e instanceof thrift.TException, "is instanceof TException");
assert.ok(e instanceof Error, "is instanceof Error");
assert.equal(typeof e.stack, "string", "has stack trace");
assert.ok(
/^TApplicationException: foo/.test(e.stack),
- "Stack trace has correct error name and message"
+ "Stack trace has correct error name and message",
);
assert.ok(
e.stack.indexOf("test/exceptions.js:7:11") !== -1,
- "stack trace starts on correct line and column"
+ "stack trace starts on correct line and column",
);
assert.equal(
e.name,
"TApplicationException",
- "has function name TApplicationException"
+ "has function name TApplicationException",
);
assert.equal(e.message, "foo", 'has error message "foo"');
assert.equal(e.type, 1, "has type 1");
@@ -53,23 +53,23 @@
const e = new thrift.TApplicationException(1, 100);
assert.ok(
e instanceof thrift.TApplicationException,
- "is instanceof TApplicationException"
+ "is instanceof TApplicationException",
);
assert.ok(e instanceof thrift.TException, "is instanceof TException");
assert.ok(e instanceof Error, "is instanceof Error");
assert.equal(typeof e.stack, "string", "has stack trace");
assert.ok(
/^TApplicationException: 100/.test(e.stack),
- "Stack trace has correct error name and message"
+ "Stack trace has correct error name and message",
);
assert.ok(
e.stack.indexOf("test/exceptions.js:7:11") !== -1,
- "stack trace starts on correct line and column"
+ "stack trace starts on correct line and column",
);
assert.equal(
e.name,
"TApplicationException",
- "has function name TApplicationException"
+ "has function name TApplicationException",
);
assert.equal(e.message, 100, "has error message 100");
assert.equal(e.type, 1, "has type 1");
@@ -83,11 +83,11 @@
assert.equal(typeof e.stack, "string", "has stack trace");
assert.ok(
/^TException: foo/.test(e.stack),
- "Stack trace has correct error name and message"
+ "Stack trace has correct error name and message",
);
assert.ok(
e.stack.indexOf("test/exceptions.js:21:11") !== -1,
- "stack trace starts on correct line and column"
+ "stack trace starts on correct line and column",
);
assert.equal(e.name, "TException", "has function name TException");
assert.equal(e.message, "foo", 'has error message "foo"');
@@ -98,22 +98,22 @@
const e = new thrift.TProtocolException(1, "foo");
assert.ok(
e instanceof thrift.TProtocolException,
- "is instanceof TProtocolException"
+ "is instanceof TProtocolException",
);
assert.ok(e instanceof Error, "is instanceof Error");
assert.equal(typeof e.stack, "string", "has stack trace");
assert.ok(
/^TProtocolException: foo/.test(e.stack),
- "Stack trace has correct error name and message"
+ "Stack trace has correct error name and message",
);
assert.ok(
e.stack.indexOf("test/exceptions.js:33:11") !== -1,
- "stack trace starts on correct line and column"
+ "stack trace starts on correct line and column",
);
assert.equal(
e.name,
"TProtocolException",
- "has function name TProtocolException"
+ "has function name TProtocolException",
);
assert.equal(e.message, "foo", 'has error message "foo"');
assert.equal(e.type, 1, "has type 1");
@@ -124,22 +124,22 @@
const e = new InputBufferUnderrunError("foo");
assert.ok(
e instanceof InputBufferUnderrunError,
- "is instanceof InputBufferUnderrunError"
+ "is instanceof InputBufferUnderrunError",
);
assert.ok(e instanceof Error, "is instanceof Error");
assert.equal(typeof e.stack, "string", "has stack trace");
assert.ok(
/^InputBufferUnderrunError: foo/.test(e.stack),
- "Stack trace has correct error name and message"
+ "Stack trace has correct error name and message",
);
assert.ok(
e.stack.indexOf("test/exceptions.js:46:11") !== -1,
- "stack trace starts on correct line and column"
+ "stack trace starts on correct line and column",
);
assert.equal(
e.name,
"InputBufferUnderrunError",
- "has function name InputBufferUnderrunError"
+ "has function name InputBufferUnderrunError",
);
assert.equal(e.message, "foo", 'has error message "foo"');
assert.end();
diff --git a/lib/nodejs/test/header.test.js b/lib/nodejs/test/header.test.js
index 12f1557..24f49be 100644
--- a/lib/nodejs/test/header.test.js
+++ b/lib/nodejs/test/header.test.js
@@ -26,11 +26,11 @@
const path = require("path");
const headerPayload = fs.readFileSync(
- path.join(__dirname, "test_header_payload")
+ path.join(__dirname, "test_header_payload"),
);
const cases = {
- "Should read headers from payload": function(assert) {
+ "Should read headers from payload": function (assert) {
const transport = new TFramedTransport();
transport.inBuf = Buffer.from(headerPayload);
@@ -39,7 +39,7 @@
assert.equals(headers.Trace, "abcde");
assert.end();
},
- "Should read different headers from different payload": function(assert) {
+ "Should read different headers from different payload": function (assert) {
const transport = new TFramedTransport();
const buf = Buffer.from(headerPayload);
buf[24] = 115; // Change Parent to Parens
@@ -52,7 +52,7 @@
assert.equals(headers.Trace, "abcde");
assert.end();
},
- "Should read headers when reading message begin": function(assert) {
+ "Should read headers when reading message begin": function (assert) {
const transport = new TFramedTransport();
transport.inBuf = Buffer.from(headerPayload);
const protocol = new THeaderProtocol(transport);
@@ -65,7 +65,7 @@
assert.equals(result.mtype, thrift.Thrift.MessageType.CALL);
assert.end();
},
- "Should be able to write headers": function(assert) {
+ "Should be able to write headers": function (assert) {
const writeTransport = new TFramedTransport();
writeTransport.setProtocolId(THeaderTransport.SubprotocolId.BINARY);
writeTransport.setWriteHeader("Hihihihi", "hohohoho");
@@ -84,7 +84,7 @@
assert.equals(headers.a, "z");
assert.end();
},
- "Separate transports should have separate headers": function(assert) {
+ "Separate transports should have separate headers": function (assert) {
const writeTransport = new TFramedTransport();
writeTransport.setProtocolId(THeaderTransport.SubprotocolId.BINARY);
writeTransport.setWriteHeader("foo", "bar");
@@ -101,8 +101,8 @@
assert.equals(otherHeaders.otherfoo, "baz");
assert.end();
},
- "Should handle large messages without crashing": function(assert) {
- const callback = function() {};
+ "Should handle large messages without crashing": function (assert) {
+ const callback = function () {};
const onData = TFramedTransport.receiver(callback);
const largeChunkSize = 2 * 100 * 1024 * 1024;
@@ -112,9 +112,9 @@
onData(Buffer.concat([sizeBuffer, largeChunk]));
assert.end();
- }
+ },
};
-Object.keys(cases).forEach(function(caseName) {
+Object.keys(cases).forEach(function (caseName) {
test(caseName, cases[caseName]);
});
diff --git a/lib/nodejs/test/helpers.js b/lib/nodejs/test/helpers.js
index f3c27b3..51a0523 100644
--- a/lib/nodejs/test/helpers.js
+++ b/lib/nodejs/test/helpers.js
@@ -22,14 +22,14 @@
module.exports.transports = {
buffered: thrift.TBufferedTransport,
- framed: thrift.TFramedTransport
+ framed: thrift.TFramedTransport,
};
module.exports.protocols = {
json: thrift.TJSONProtocol,
binary: thrift.TBinaryProtocol,
compact: thrift.TCompactProtocol,
- header: thrift.THeaderProtocol
+ header: thrift.THeaderProtocol,
};
module.exports.ecmaMode = process.argv.includes("--es6") ? "es6" : "es5";
diff --git a/lib/nodejs/test/int64.test.js b/lib/nodejs/test/int64.test.js
index 27ad28c..21d4d58 100644
--- a/lib/nodejs/test/int64.test.js
+++ b/lib/nodejs/test/int64.test.js
@@ -23,7 +23,7 @@
const test = require("tape");
const cases = {
- "should correctly generate Int64 constants": function(assert) {
+ "should correctly generate Int64 constants": function (assert) {
const EXPECTED_SMALL_INT64_AS_NUMBER = 42;
const EXPECTED_SMALL_INT64 = new Int64(42);
const EXPECTED_MAX_JS_SAFE_INT64 = new Int64(Number.MAX_SAFE_INTEGER);
@@ -39,7 +39,7 @@
EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64,
EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64,
EXPECTED_MAX_SIGNED_INT64,
- EXPECTED_MIN_SIGNED_INT64
+ EXPECTED_MIN_SIGNED_INT64,
];
assert.ok(EXPECTED_SMALL_INT64.equals(i64types.SMALL_INT64));
@@ -47,27 +47,27 @@
assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(i64types.MIN_JS_SAFE_INT64));
assert.ok(
EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals(
- i64types.MAX_JS_SAFE_PLUS_ONE_INT64
- )
+ i64types.MAX_JS_SAFE_PLUS_ONE_INT64,
+ ),
);
assert.ok(
EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals(
- i64types.MIN_JS_SAFE_MINUS_ONE_INT64
- )
+ i64types.MIN_JS_SAFE_MINUS_ONE_INT64,
+ ),
);
assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(i64types.MAX_SIGNED_INT64));
assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(i64types.MIN_SIGNED_INT64));
assert.equal(
EXPECTED_SMALL_INT64_AS_NUMBER,
- i64types.SMALL_INT64.toNumber()
+ i64types.SMALL_INT64.toNumber(),
);
assert.equal(
Number.MAX_SAFE_INTEGER,
- i64types.MAX_JS_SAFE_INT64.toNumber()
+ i64types.MAX_JS_SAFE_INT64.toNumber(),
);
assert.equal(
Number.MIN_SAFE_INTEGER,
- i64types.MIN_JS_SAFE_INT64.toNumber()
+ i64types.MIN_JS_SAFE_INT64.toNumber(),
);
for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
@@ -79,14 +79,14 @@
assert.ok(
i64types.INT64_2_INT64_MAP[
JSONInt64.toDecimalString(int64Object)
- ].equals(int64Object)
+ ].equals(int64Object),
);
}
assert.end();
- }
+ },
};
-Object.keys(cases).forEach(function(caseName) {
+Object.keys(cases).forEach(function (caseName) {
test(caseName, cases[caseName]);
});
diff --git a/lib/nodejs/test/server.js b/lib/nodejs/test/server.js
index 677839a..c8e7808 100644
--- a/lib/nodejs/test/server.js
+++ b/lib/nodejs/test/server.js
@@ -29,12 +29,12 @@
.option(
"-p, --protocol <protocol>",
"Set thrift protocol (binary|compact|json)",
- "binary"
+ "binary",
)
.option(
"-t, --transport <transport>",
"Set thrift transport (buffered|framed|http)",
- "buffered"
+ "buffered",
)
.option("--ssl", "use ssl transport")
.option("--port <port>", "Set thrift server port", 9090)
@@ -42,7 +42,7 @@
.option(
"-t, --type <type>",
"Select server type (http|multiplex|tcp|websocket)",
- "tcp"
+ "tcp",
)
.option("--callback", "test with callback style functions")
.option("--es6", "Use es6 code")
@@ -68,7 +68,7 @@
let options = {
transport: helpers.transports[program.transport],
- protocol: helpers.protocols[program.protocol]
+ protocol: helpers.protocols[program.protocol],
};
if (type === "http" || type === "websocket") {
@@ -78,30 +78,30 @@
options = {
services: { "/test": options },
cors: {
- "*": true
- }
+ "*": true,
+ },
};
}
let processor;
if (type === "multiplex") {
const SecondServiceHandler = {
- secondtestString: function(thing, result) {
+ secondtestString: function (thing, result) {
console.log('testString("' + thing + '")');
result(null, 'testString("' + thing + '")');
- }
+ },
};
processor = new thrift.MultiplexedProcessor();
processor.registerProcessor(
"ThriftTest",
- new ThriftTest.Processor(ThriftTestHandler)
+ new ThriftTest.Processor(ThriftTestHandler),
);
processor.registerProcessor(
"SecondService",
- new SecondService.Processor(SecondServiceHandler)
+ new SecondService.Processor(SecondServiceHandler),
);
}
@@ -114,7 +114,7 @@
) {
options.tls = {
key: fs.readFileSync(path.resolve(__dirname, "server.key")),
- cert: fs.readFileSync(path.resolve(__dirname, "server.crt"))
+ cert: fs.readFileSync(path.resolve(__dirname, "server.crt")),
};
}
}
diff --git a/lib/nodejs/test/test-cases.js b/lib/nodejs/test/test-cases.js
index 02c566f..98077f7 100644
--- a/lib/nodejs/test/test-cases.js
+++ b/lib/nodejs/test/test-cases.js
@@ -65,9 +65,9 @@
a: "123",
"a b": "with spaces ",
same: "same",
- "0": "numeric key",
+ 0: "numeric key",
longValue: stringTest,
- stringTest: "long key"
+ stringTest: "long key",
});
const simple = [
@@ -93,9 +93,9 @@
["testI64", new Int64(new Buffer([0, 0x20, 0, 0, 0, 0, 0, 1]))], // 2^53+1
[
"testI64",
- new Int64(new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]))
+ new Int64(new Buffer([0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])),
], // -2^53-1
- ["testTypedef", 69]
+ ["testTypedef", 69],
];
const mapout = {};
@@ -106,21 +106,21 @@
const deep = [
[
"testList",
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
- ]
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
+ ],
];
const deepUnordered = [
["testMap", mapout],
["testSet", [1, 2, 3]],
- ["testStringMap", mapTestInput]
+ ["testStringMap", mapTestInput],
];
const out = new ttypes.Xtruct({
string_thing: "Zero",
byte_thing: 1,
i32_thing: -3,
- i64_thing: 1000000
+ i64_thing: 1000000,
});
const out2 = new ttypes.Xtruct2();
@@ -129,44 +129,44 @@
out2.i32_thing = 5;
const crazy = new ttypes.Insanity({
- userMap: { "5": 5, "8": 8 },
+ userMap: { 5: 5, 8: 8 },
xtructs: [
new ttypes.Xtruct({
string_thing: "Goodbye4",
byte_thing: 4,
i32_thing: 4,
- i64_thing: 4
+ i64_thing: 4,
}),
new ttypes.Xtruct({
string_thing: "Hello2",
byte_thing: 2,
i32_thing: 2,
- i64_thing: 2
- })
- ]
+ i64_thing: 2,
+ }),
+ ],
});
const crazy2 = new ttypes.Insanity({
- userMap: { "5": 5, "8": 8 },
+ userMap: { 5: 5, 8: 8 },
xtructs: [
{
string_thing: "Goodbye4",
byte_thing: 4,
i32_thing: 4,
- i64_thing: 4
+ i64_thing: 4,
},
{
string_thing: "Hello2",
byte_thing: 2,
i32_thing: 2,
- i64_thing: 2
- }
- ]
+ i64_thing: 2,
+ },
+ ],
});
const insanity = {
- "1": { "2": crazy, "3": crazy },
- "2": { "6": { userMap: {}, xtructs: [] } }
+ 1: { 2: crazy, 3: crazy },
+ 2: { 6: { userMap: {}, xtructs: [] } },
};
module.exports.simple = simple;
diff --git a/lib/nodejs/test/test_driver.js b/lib/nodejs/test/test_driver.js
index 7c9a919..0593aea 100644
--- a/lib/nodejs/test/test_driver.js
+++ b/lib/nodejs/test/test_driver.js
@@ -34,18 +34,18 @@
const Int64 = require("node-int64");
const testCases = require("./test-cases");
-exports.ThriftTestDriver = function(client, callback) {
+exports.ThriftTestDriver = function (client, callback) {
test(
"NodeJS Style Callback Client Tests",
{ skip: helpers.ecmaMode === "es6" },
- function(assert) {
+ function (assert) {
const checkRecursively = makeRecursiveCheck(assert);
function makeAsserter(assertionFn) {
- return function(c) {
+ return function (c) {
const fnName = c[0];
const expected = c[1];
- client[fnName](expected, function(err, actual) {
+ client[fnName](expected, function (err, actual) {
assert.error(err, fnName + ": no callback error");
assertionFn(actual, expected, fnName);
});
@@ -53,18 +53,18 @@
}
testCases.simple.forEach(
- makeAsserter(function(a, e, m) {
+ makeAsserter(function (a, e, m) {
if (a instanceof Int64) {
const e64 = e instanceof Int64 ? e : new Int64(e);
assert.deepEqual(a.buffer, e64.buffer, m);
} else {
assert.equal(a, e, m);
}
- })
+ }),
);
testCases.deep.forEach(makeAsserter(assert.deepEqual));
testCases.deepUnordered.forEach(
- makeAsserter(makeUnorderedDeepEqual(assert))
+ makeAsserter(makeUnorderedDeepEqual(assert)),
);
const arr = [];
@@ -72,106 +72,106 @@
arr[i] = 255 - i;
}
let buf = new Buffer(arr);
- client.testBinary(buf, function(err, response) {
+ client.testBinary(buf, function (err, response) {
assert.error(err, "testBinary: no callback error");
assert.equal(response.length, 256, "testBinary");
assert.deepEqual(response, buf, "testBinary(Buffer)");
});
buf = new Buffer(arr);
- client.testBinary(buf.toString("binary"), function(err, response) {
+ client.testBinary(buf.toString("binary"), function (err, response) {
assert.error(err, "testBinary: no callback error");
assert.equal(response.length, 256, "testBinary");
assert.deepEqual(response, buf, "testBinary(string)");
});
- client.testMapMap(42, function(err, response) {
+ client.testMapMap(42, function (err, response) {
const expected = {
- "4": { "1": 1, "2": 2, "3": 3, "4": 4 },
- "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 }
+ 4: { 1: 1, 2: 2, 3: 3, 4: 4 },
+ "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 },
};
assert.error(err, "testMapMap: no callback error");
assert.deepEqual(expected, response, "testMapMap");
});
- client.testStruct(testCases.out, function(err, response) {
+ client.testStruct(testCases.out, function (err, response) {
assert.error(err, "testStruct: no callback error");
checkRecursively(testCases.out, response, "testStruct");
});
- client.testNest(testCases.out2, function(err, response) {
+ client.testNest(testCases.out2, function (err, response) {
assert.error(err, "testNest: no callback error");
checkRecursively(testCases.out2, response, "testNest");
});
- client.testInsanity(testCases.crazy, function(err, response) {
+ client.testInsanity(testCases.crazy, function (err, response) {
assert.error(err, "testInsanity: no callback error");
checkRecursively(testCases.insanity, response, "testInsanity");
});
- client.testInsanity(testCases.crazy2, function(err, response) {
+ client.testInsanity(testCases.crazy2, function (err, response) {
assert.error(err, "testInsanity2: no callback error");
checkRecursively(testCases.insanity, response, "testInsanity2");
});
- client.testException("TException", function(err, response) {
+ client.testException("TException", function (err, response) {
assert.ok(
err instanceof TException,
- "testException: correct error type"
+ "testException: correct error type",
);
assert.ok(!response, "testException: no response");
});
- client.testException("Xception", function(err, response) {
+ client.testException("Xception", function (err, response) {
assert.ok(
err instanceof ttypes.Xception,
- "testException: correct error type"
+ "testException: correct error type",
);
assert.ok(!response, "testException: no response");
assert.equal(err.errorCode, 1001, "testException: correct error code");
assert.equal(
"Xception",
err.message,
- "testException: correct error message"
+ "testException: correct error message",
);
});
- client.testException("no Exception", function(err, response) {
+ client.testException("no Exception", function (err, response) {
assert.error(err, "testException: no callback error");
assert.ok(!response, "testException: no response");
});
- client.testOneway(0, function(err, response) {
+ client.testOneway(0, function (err, response) {
assert.error(err, "testOneway: no callback error");
assert.strictEqual(response, undefined, "testOneway: void response");
});
- checkOffByOne(function(done) {
- client.testI32(-1, function(err, response) {
+ checkOffByOne(function (done) {
+ client.testI32(-1, function (err, response) {
assert.error(err, "checkOffByOne: no callback error");
assert.equal(-1, response);
assert.end();
done();
});
}, callback);
- }
+ },
);
// ES6 does not support callback style
if (helpers.ecmaMode === "es6") {
- checkOffByOne(done => done(), callback);
+ checkOffByOne((done) => done(), callback);
}
};
-exports.ThriftTestDriverPromise = function(client, callback) {
- test("Promise Client Tests", function(assert) {
+exports.ThriftTestDriverPromise = function (client, callback) {
+ test("Promise Client Tests", function (assert) {
const checkRecursively = makeRecursiveCheck(assert);
function makeAsserter(assertionFn) {
- return function(c) {
+ return function (c) {
const fnName = c[0];
const expected = c[1];
client[fnName](expected)
- .then(function(actual) {
+ .then(function (actual) {
assertionFn(actual, expected, fnName);
})
.catch(() => assert.fail("fnName"));
@@ -179,63 +179,63 @@
}
testCases.simple.forEach(
- makeAsserter(function(a, e, m) {
+ makeAsserter(function (a, e, m) {
if (a instanceof Int64) {
const e64 = e instanceof Int64 ? e : new Int64(e);
assert.deepEqual(a.buffer, e64.buffer, m);
} else {
assert.equal(a, e, m);
}
- })
+ }),
);
testCases.deep.forEach(makeAsserter(assert.deepEqual));
testCases.deepUnordered.forEach(
- makeAsserter(makeUnorderedDeepEqual(assert))
+ makeAsserter(makeUnorderedDeepEqual(assert)),
);
client
.testStruct(testCases.out)
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.out, response, "testStruct");
})
.catch(() => assert.fail("testStruct"));
client
.testNest(testCases.out2)
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.out2, response, "testNest");
})
.catch(() => assert.fail("testNest"));
client
.testInsanity(testCases.crazy)
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.insanity, response, "testInsanity");
})
.catch(() => assert.fail("testInsanity"));
client
.testInsanity(testCases.crazy2)
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.insanity, response, "testInsanity2");
})
.catch(() => assert.fail("testInsanity2"));
client
.testException("TException")
- .then(function() {
+ .then(function () {
assert.fail("testException: TException");
})
- .catch(function(err) {
+ .catch(function (err) {
assert.ok(err instanceof TException);
});
client
.testException("Xception")
- .then(function() {
+ .then(function () {
assert.fail("testException: Xception");
})
- .catch(function(err) {
+ .catch(function (err) {
assert.ok(err instanceof ttypes.Xception);
assert.equal(err.errorCode, 1001);
assert.equal("Xception", err.message);
@@ -243,22 +243,22 @@
client
.testException("no Exception")
- .then(function(response) {
+ .then(function (response) {
assert.equal(undefined, response); //void
})
.catch(() => assert.fail("testException"));
client
.testOneway(0)
- .then(function(response) {
+ .then(function (response) {
assert.strictEqual(response, undefined, "testOneway: void response");
})
.catch(() => assert.fail("testOneway: should not reject"));
- checkOffByOne(function(done) {
+ checkOffByOne(function (done) {
client
.testI32(-1)
- .then(function(response) {
+ .then(function (response) {
assert.equal(-1, response);
assert.end();
done();
@@ -272,7 +272,7 @@
// =========================================================
function makeRecursiveCheck(assert) {
- return function(map1, map2, msg) {
+ return function (map1, map2, msg) {
const equal = checkRecursively(map1, map2);
assert.ok(equal, msg);
@@ -295,7 +295,7 @@
return map1 == map2;
}
} else {
- return Object.keys(map1).every(function(key) {
+ return Object.keys(map1).every(function (key) {
return checkRecursively(map1[key], map2[key]);
});
}
@@ -319,7 +319,7 @@
* Because this is the last test against the server, when it completes
* the entire suite is complete by definition (the tests run serially).
*/
- done(function() {
+ done(function () {
test_complete = true;
});
@@ -334,7 +334,7 @@
callback(
"Server test failed to complete after " +
(retry_limit * retry_interval) / 1000 +
- " seconds"
+ " seconds",
);
}
}
@@ -344,7 +344,7 @@
}
function makeUnorderedDeepEqual(assert) {
- return function(actual, expected, name) {
+ return function (actual, expected, name) {
assert.equal(actual.length, expected.length, name);
for (const k in actual) {
let found = false;
diff --git a/lib/nodejs/test/test_handler.js b/lib/nodejs/test/test_handler.js
index 317a7c8..a6a6fc2 100644
--- a/lib/nodejs/test/test_handler.js
+++ b/lib/nodejs/test/test_handler.js
@@ -24,7 +24,7 @@
const TException = require("thrift").Thrift.TException;
function makeSyncHandler() {
- return function(thing) {
+ return function (thing) {
return thing;
};
}
@@ -36,11 +36,11 @@
testMulti: testMulti,
testException: testException,
testMultiException: testMultiException,
- testOneway: testOneway
+ testOneway: testOneway,
};
function makeAsyncHandler(label) {
- return function(thing, result) {
+ return function (thing, result) {
thing = syncHandlers[label](thing);
result(null, thing);
};
@@ -51,7 +51,7 @@
testMulti: testMultiAsync,
testException: testExceptionAsync,
testMultiException: testMultiExceptionAsync,
- testOneway: testOnewayAsync
+ testOneway: testOnewayAsync,
};
const identityHandlers = [
@@ -69,7 +69,7 @@
"testSet",
"testList",
"testEnum",
- "testTypedef"
+ "testTypedef",
];
function testVoid() {
@@ -208,12 +208,12 @@
testOneway(sleepFor);
}
-identityHandlers.forEach(function(label) {
+identityHandlers.forEach(function (label) {
syncHandlers[label] = makeSyncHandler(label);
asyncHandlers[label] = makeAsyncHandler(label);
});
-["testMapMap", "testInsanity"].forEach(function(label) {
+["testMapMap", "testInsanity"].forEach(function (label) {
asyncHandlers[label] = makeAsyncHandler(label);
});
diff --git a/lib/nodets/test/client.ts b/lib/nodets/test/client.ts
index 4fa3c28..a95567f 100644
--- a/lib/nodets/test/client.ts
+++ b/lib/nodets/test/client.ts
@@ -39,15 +39,15 @@
var options = {
transport: Thrift.TBufferedTransport,
- protocol: Thrift.TBinaryProtocol
+ protocol: Thrift.TBinaryProtocol,
};
var testDriver = promise ? ThriftTestDriverPromise : ThriftTestDriver;
var connection = thrift.createConnection("localhost", port, options);
-connection.on("error", function(err: string) {
- assert(false, err);
+connection.on("error", function (err: string) {
+ assert(false, err);
});
var client = thrift.createClient(ThriftTest.Client, connection);
@@ -60,4 +60,4 @@
});
}
-exports.expressoTest = function() {};
+exports.expressoTest = function () {};
diff --git a/lib/nodets/test/int64.test.ts b/lib/nodets/test/int64.test.ts
index d209234..bb03458 100644
--- a/lib/nodets/test/int64.test.ts
+++ b/lib/nodets/test/int64.test.ts
@@ -18,18 +18,26 @@
*/
import Int64 = require("node-int64");
-import JSONInt64 = require('json-int64');
+import JSONInt64 = require("json-int64");
import i64types = require("./gen-nodejs/Int64Test_types");
import test = require("tape");
const cases = {
- "should correctly generate Int64 constants": function(assert) {
+ "should correctly generate Int64 constants": function (assert) {
const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42;
const EXPECTED_SMALL_INT64: Int64 = new Int64(42);
- const EXPECTED_MAX_JS_SAFE_INT64: Int64 = new Int64(Number.MAX_SAFE_INTEGER);
- const EXPECTED_MIN_JS_SAFE_INT64: Int64 = new Int64(Number.MIN_SAFE_INTEGER);
- const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: Int64 = new Int64("0020000000000000"); // hex-encoded
- const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: Int64 = new Int64("ffe0000000000000"); // hex-encoded 2's complement
+ const EXPECTED_MAX_JS_SAFE_INT64: Int64 = new Int64(
+ Number.MAX_SAFE_INTEGER,
+ );
+ const EXPECTED_MIN_JS_SAFE_INT64: Int64 = new Int64(
+ Number.MIN_SAFE_INTEGER,
+ );
+ const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: Int64 = new Int64(
+ "0020000000000000",
+ ); // hex-encoded
+ const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: Int64 = new Int64(
+ "ffe0000000000000",
+ ); // hex-encoded 2's complement
const EXPECTED_MAX_SIGNED_INT64: Int64 = new Int64("7fffffffffffffff"); // hex-encoded
const EXPECTED_MIN_SIGNED_INT64: Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement
const EXPECTED_INT64_LIST: Int64[] = [
@@ -39,7 +47,7 @@
EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64,
EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64,
EXPECTED_MAX_SIGNED_INT64,
- EXPECTED_MIN_SIGNED_INT64
+ EXPECTED_MIN_SIGNED_INT64,
];
assert.ok(EXPECTED_SMALL_INT64.equals(i64types.SMALL_INT64));
@@ -47,42 +55,46 @@
assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(i64types.MIN_JS_SAFE_INT64));
assert.ok(
EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals(
- i64types.MAX_JS_SAFE_PLUS_ONE_INT64
- )
+ i64types.MAX_JS_SAFE_PLUS_ONE_INT64,
+ ),
);
assert.ok(
EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals(
- i64types.MIN_JS_SAFE_MINUS_ONE_INT64
- )
+ i64types.MIN_JS_SAFE_MINUS_ONE_INT64,
+ ),
);
assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(i64types.MAX_SIGNED_INT64));
assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(i64types.MIN_SIGNED_INT64));
assert.equal(
EXPECTED_SMALL_INT64_AS_NUMBER,
- i64types.SMALL_INT64.toNumber()
+ i64types.SMALL_INT64.toNumber(),
);
assert.equal(
Number.MAX_SAFE_INTEGER,
- i64types.MAX_JS_SAFE_INT64.toNumber()
+ i64types.MAX_JS_SAFE_INT64.toNumber(),
);
assert.equal(
Number.MIN_SAFE_INTEGER,
- i64types.MIN_JS_SAFE_INT64.toNumber()
+ i64types.MIN_JS_SAFE_INT64.toNumber(),
);
for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
assert.ok(EXPECTED_INT64_LIST[i].equals(i64types.INT64_LIST[i]));
}
- for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i){
+ for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
let int64Object = EXPECTED_INT64_LIST[i];
- assert.ok(i64types.INT64_2_INT64_MAP[JSONInt64.toDecimalString(int64Object)].equals(int64Object));
+ assert.ok(
+ i64types.INT64_2_INT64_MAP[
+ JSONInt64.toDecimalString(int64Object)
+ ].equals(int64Object),
+ );
}
assert.end();
- }
+ },
};
-Object.keys(cases).forEach(function(caseName) {
+Object.keys(cases).forEach(function (caseName) {
test(caseName, cases[caseName]);
});
diff --git a/lib/nodets/test/server.ts b/lib/nodets/test/server.ts
index 2da53ae..79457ce 100644
--- a/lib/nodets/test/server.ts
+++ b/lib/nodets/test/server.ts
@@ -1,26 +1,33 @@
import thrift = require("thrift");
-var program = require('commander');
-import ThriftTest = require('./gen-nodejs/ThriftTest');
-import test_handler = require('./test_handler');
-
+var program = require("commander");
+import ThriftTest = require("./gen-nodejs/ThriftTest");
+import test_handler = require("./test_handler");
program
- .option('--port <port>', 'Set thrift server port', 9090)
- .option('--promise', 'test with promise style functions')
- .option('--protocol', '"Set thrift protocol (binary) [protocol]"')
+ .option("--port <port>", "Set thrift server port", 9090)
+ .option("--promise", "test with promise style functions")
+ .option("--protocol", '"Set thrift protocol (binary) [protocol]"')
.parse(process.argv);
var port: number = program.port;
var options: thrift.ServerOptions = {
transport: thrift.TBufferedTransport,
- protocol: thrift.TBinaryProtocol
+ protocol: thrift.TBinaryProtocol,
};
var server: thrift.Server;
if (program.promise) {
- server = thrift.createServer(ThriftTest.Processor, new test_handler.AsyncThriftTestHandler(), options);
+ server = thrift.createServer(
+ ThriftTest.Processor,
+ new test_handler.AsyncThriftTestHandler(),
+ options,
+ );
} else {
- server = thrift.createServer(ThriftTest.Processor, new test_handler.SyncThriftTestHandler(), options);
+ server = thrift.createServer(
+ ThriftTest.Processor,
+ new test_handler.SyncThriftTestHandler(),
+ options,
+ );
}
server.listen(port);
diff --git a/lib/nodets/test/test-cases.ts b/lib/nodets/test/test-cases.ts
index 44f254e..98f54af 100644
--- a/lib/nodets/test/test-cases.ts
+++ b/lib/nodets/test/test-cases.ts
@@ -1,91 +1,100 @@
-'use strict';
+"use strict";
-import ttypes = require('./gen-nodejs/ThriftTest_types');
-import Int64 = require('node-int64');
+import ttypes = require("./gen-nodejs/ThriftTest_types");
+import Int64 = require("node-int64");
//all Languages in UTF-8
/*jshint -W100 */
-export var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " +
- "Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, " +
- "Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, " +
- "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, " +
- "Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, " +
- "Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, " +
- "Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, " +
- "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " +
- "Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, " +
- "Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, " +
- "Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, " +
- "ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, " +
- "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " +
- "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa " +
- "Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, مازِرونی, Bahasa " +
- "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, " +
- "Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, " +
- "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " +
- "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " +
- "Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " +
- "English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, " +
- "Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " +
- "Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, " +
- "Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " +
- "Bân-lâm-gú, 粵語";
+export var stringTest =
+ "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, " +
+ "Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, " +
+ "Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, " +
+ "বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, " +
+ "Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, " +
+ "Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, " +
+ "Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, " +
+ "Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, " +
+ "Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, " +
+ "Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, " +
+ "Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, " +
+ "ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, " +
+ "Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, " +
+ "Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa " +
+ "Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, مازِرونی, Bahasa " +
+ "Melayu, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, " +
+ "Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, " +
+ "Occitan, Иронау, Papiamentu, Deitsch, Polski, پنجابی, پښتو, " +
+ "Norfuk / Pitkern, Português, Runa Simi, Rumantsch, Romani, Română, " +
+ "Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple " +
+ "English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, " +
+ "Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, " +
+ "Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, " +
+ "Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " +
+ "Bân-lâm-gú, 粵語";
/*jshint +W100 */
-export var specialCharacters = 'quote: \" backslash:' +
- ' forwardslash-escaped: \/ ' +
- ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
- ' now-all-of-them-together: "\\\/\b\n\r\t' +
- ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><' +
- ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ ';
+export var specialCharacters =
+ 'quote: \" backslash:' +
+ " forwardslash-escaped: \/ " +
+ " backspace: \b formfeed: \f newline: \n return: \r tab: " +
+ ' now-all-of-them-together: "\\\/\b\n\r\t' +
+ " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><" +
+ ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ ';
export var mapTestInput = {
- "a":"123", "a b":"with spaces ", "same":"same", "0":"numeric key",
- "longValue":stringTest, stringTest:"long key"
+ a: "123",
+ "a b": "with spaces ",
+ same: "same",
+ "0": "numeric key",
+ longValue: stringTest,
+ stringTest: "long key",
};
export var simple = [
- ['testVoid', undefined],
- ['testString', 'Test'],
- ['testString', ''],
- ['testString', stringTest],
- ['testString', specialCharacters],
- ['testByte', 1],
- ['testByte', 0],
- ['testByte', -1],
- ['testByte', -127],
- ['testI32', -1],
- ['testDouble', -5.2098523],
- ['testDouble', 7.012052175215044],
- ['testEnum', ttypes.Numberz.ONE]
+ ["testVoid", undefined],
+ ["testString", "Test"],
+ ["testString", ""],
+ ["testString", stringTest],
+ ["testString", specialCharacters],
+ ["testByte", 1],
+ ["testByte", 0],
+ ["testByte", -1],
+ ["testByte", -127],
+ ["testI32", -1],
+ ["testDouble", -5.2098523],
+ ["testDouble", 7.012052175215044],
+ ["testEnum", ttypes.Numberz.ONE],
];
export var simpleLoose = [
- ['testI64', 5],
- ['testI64', -5],
- ['testI64', 734359738368],
- ['testI64', -34359738368],
- ['testI64', -734359738368],
- ['testTypedef', 69]
-]
+ ["testI64", 5],
+ ["testI64", -5],
+ ["testI64", 734359738368],
+ ["testI64", -34359738368],
+ ["testI64", -734359738368],
+ ["testTypedef", 69],
+];
-var mapout: {[key: number]: number; } = {};
+var mapout: { [key: number]: number } = {};
for (var i = 0; i < 5; ++i) {
- mapout[i] = i-10;
+ mapout[i] = i - 10;
}
export var deep = [
- ['testMap', mapout],
- ['testSet', [1,2,3]],
- ['testList', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]],
- ['testStringMap', mapTestInput]
+ ["testMap", mapout],
+ ["testSet", [1, 2, 3]],
+ [
+ "testList",
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
+ ],
+ ["testStringMap", mapTestInput],
];
export var out = new ttypes.Xtruct({
- string_thing: 'Zero',
+ string_thing: "Zero",
byte_thing: 1,
i32_thing: -3,
- i64_thing: new Int64(1000000)
+ i64_thing: new Int64(1000000),
});
export var out2 = new ttypes.Xtruct2();
@@ -94,21 +103,24 @@
out2.i32_thing = 5;
export var crazy = new ttypes.Insanity({
- "userMap":{ "5":new Int64(5), "8":new Int64(8) },
- "xtructs":[new ttypes.Xtruct({
- "string_thing":"Goodbye4",
- "byte_thing":4,
- "i32_thing":4,
- "i64_thing":new Int64(4)
- }), new ttypes.Xtruct({
- "string_thing":"Hello2",
- "byte_thing":2,
- "i32_thing":2,
- "i64_thing":new Int64(2)
- })]
+ userMap: { "5": new Int64(5), "8": new Int64(8) },
+ xtructs: [
+ new ttypes.Xtruct({
+ string_thing: "Goodbye4",
+ byte_thing: 4,
+ i32_thing: 4,
+ i64_thing: new Int64(4),
+ }),
+ new ttypes.Xtruct({
+ string_thing: "Hello2",
+ byte_thing: 2,
+ i32_thing: 2,
+ i64_thing: new Int64(2),
+ }),
+ ],
});
export var insanity: any = {
- "1":{ "2": crazy, "3": crazy },
- "2":{ "6":{ "userMap":{}, "xtructs":[] } }
+ "1": { "2": crazy, "3": crazy },
+ "2": { "6": { userMap: {}, xtructs: [] } },
};
diff --git a/lib/nodets/test/test_driver.ts b/lib/nodets/test/test_driver.ts
index 2c41526..604d5e5 100644
--- a/lib/nodets/test/test_driver.ts
+++ b/lib/nodets/test/test_driver.ts
@@ -17,14 +17,14 @@
* under the License.
*/
- // This is the Node.js test driver for the standard Apache Thrift
- // test service. The driver invokes every function defined in the
- // Thrift Test service with a representative range of parameters.
- //
- // The ThriftTestDriver function requires a client object
- // connected to a server hosting the Thrift Test service and
- // supports an optional callback function which is called with
- // a status message when the test is complete.
+// This is the Node.js test driver for the standard Apache Thrift
+// test service. The driver invokes every function defined in the
+// Thrift Test service with a representative range of parameters.
+//
+// The ThriftTestDriver function requires a client object
+// connected to a server hosting the Thrift Test service and
+// supports an optional callback function which is called with
+// a status message when the test is complete.
import test = require("tape");
import ttypes = require("./gen-nodejs/ThriftTest_types");
@@ -35,107 +35,118 @@
var Int64 = require("node-int64");
import testCases = require("./test-cases");
-export function ThriftTestDriver(client: ThriftTest.Client, callback: (status: string) => void) {
-
- test("NodeJS Style Callback Client Tests", function(assert) {
-
+export function ThriftTestDriver(
+ client: ThriftTest.Client,
+ callback: (status: string) => void,
+) {
+ test("NodeJS Style Callback Client Tests", function (assert) {
var checkRecursively = makeRecursiveCheck(assert);
function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) {
- return function(c: (string | any)[]) {
+ return function (c: (string | any)[]) {
var fnName = c[0];
var expected = c[1];
- (<any>client)[fnName](expected, function(err: any, actual: any) {
+ (<any>client)[fnName](expected, function (err: any, actual: any) {
assert.error(err, fnName + ": no callback error");
assertionFn(actual, expected, fnName);
- })
+ });
};
}
testCases.simple.forEach(makeAsserter(assert.equal));
- testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){
- assert.ok(a == e, m);
- }));
+ testCases.simpleLoose.forEach(
+ makeAsserter(function (a, e, m) {
+ assert.ok(a == e, m);
+ }),
+ );
testCases.deep.forEach(makeAsserter(assert.deepEqual));
- client.testMapMap(42, function(err, response) {
+ client.testMapMap(42, function (err, response) {
var expected: typeof response = {
- "4": {"1":1, "2":2, "3":3, "4":4},
- "-4": {"-4":-4, "-3":-3, "-2":-2, "-1":-1}
+ "4": { "1": 1, "2": 2, "3": 3, "4": 4 },
+ "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 },
};
- assert.error(err, 'testMapMap: no callback error');
+ assert.error(err, "testMapMap: no callback error");
assert.deepEqual(expected, response, "testMapMap");
});
- client.testStruct(testCases.out, function(err, response) {
+ client.testStruct(testCases.out, function (err, response) {
assert.error(err, "testStruct: no callback error");
checkRecursively(testCases.out, response, "testStruct");
});
- client.testNest(testCases.out2, function(err, response) {
+ client.testNest(testCases.out2, function (err, response) {
assert.error(err, "testNest: no callback error");
checkRecursively(testCases.out2, response, "testNest");
});
- client.testInsanity(testCases.crazy, function(err, response) {
+ client.testInsanity(testCases.crazy, function (err, response) {
assert.error(err, "testInsanity: no callback error");
checkRecursively(testCases.insanity, response, "testInsanity");
});
- client.testException("TException", function(err, response) {
- assert.ok(err instanceof TException, 'testException: correct error type');
- assert.ok(!Boolean(response), 'testException: no response');
+ client.testException("TException", function (err, response) {
+ assert.ok(err instanceof TException, "testException: correct error type");
+ assert.ok(!Boolean(response), "testException: no response");
});
- client.testException("Xception", function(err, response) {
- assert.ok(err instanceof ttypes.Xception, 'testException: correct error type');
- assert.ok(!Boolean(response), 'testException: no response');
- assert.equal(err.errorCode, 1001, 'testException: correct error code');
- assert.equal('Xception', err.message, 'testException: correct error message');
+ client.testException("Xception", function (err, response) {
+ assert.ok(
+ err instanceof ttypes.Xception,
+ "testException: correct error type",
+ );
+ assert.ok(!Boolean(response), "testException: no response");
+ assert.equal(err.errorCode, 1001, "testException: correct error code");
+ assert.equal(
+ "Xception",
+ err.message,
+ "testException: correct error message",
+ );
});
- client.testException("no Exception", function(err, response) {
- assert.error(err, 'testException: no callback error');
- assert.ok(!Boolean(response), 'testException: no response');
+ client.testException("no Exception", function (err, response) {
+ assert.error(err, "testException: no callback error");
+ assert.ok(!Boolean(response), "testException: no response");
});
- client.testOneway(0, function(err, response) {
- assert.error(err, 'testOneway: no callback error');
- assert.strictEqual(response, undefined, 'testOneway: void response');
+ client.testOneway(0, function (err, response) {
+ assert.error(err, "testOneway: no callback error");
+ assert.strictEqual(response, undefined, "testOneway: void response");
});
- checkOffByOne(function(done) {
- client.testI32(-1, function(err, response) {
+ checkOffByOne(function (done) {
+ client.testI32(-1, function (err, response) {
assert.error(err, "checkOffByOne: no callback error");
assert.equal(-1, response);
assert.end();
done();
});
}, callback);
-
});
-};
+}
-export function ThriftTestDriverPromise(client: ThriftTest.Client, callback: (status: string) => void) {
-
- test("Q Promise Client Tests", function(assert) {
-
+export function ThriftTestDriverPromise(
+ client: ThriftTest.Client,
+ callback: (status: string) => void,
+) {
+ test("Q Promise Client Tests", function (assert) {
var checkRecursively = makeRecursiveCheck(assert);
function fail(msg: string) {
- return function(error, response) {
+ return function (error, response) {
if (error !== null) {
assert.fail(msg);
}
- }
+ };
}
function makeAsserter(assertionFn: (a: any, b: any, msg?: string) => void) {
- return function(c: (string | any)[]) {
+ return function (c: (string | any)[]) {
var fnName = c[0];
var expected = c[1];
- (<any>client)[fnName](expected)
- .then(function(actual: any) {
+ (<any>client)
+ [fnName](expected)
+ .then(function (actual: any) {
assertionFn(actual, expected, fnName);
})
.fail(fail("fnName"));
@@ -143,73 +154,73 @@
}
testCases.simple.forEach(makeAsserter(assert.equal));
- testCases.simpleLoose.forEach(makeAsserter(function(a, e, m){
- assert.ok(a == e, m);
- }));
+ testCases.simpleLoose.forEach(
+ makeAsserter(function (a, e, m) {
+ assert.ok(a == e, m);
+ }),
+ );
testCases.deep.forEach(makeAsserter(assert.deepEqual));
Q.resolve(client.testStruct(testCases.out))
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.out, response, "testStruct");
})
.fail(fail("testStruct"));
Q.resolve(client.testNest(testCases.out2))
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.out2, response, "testNest");
})
.fail(fail("testNest"));
Q.resolve(client.testInsanity(testCases.crazy))
- .then(function(response) {
+ .then(function (response) {
checkRecursively(testCases.insanity, response, "testInsanity");
})
.fail(fail("testInsanity"));
Q.resolve(client.testException("TException"))
- .then(function(response) {
+ .then(function (response) {
fail("testException: TException");
})
- .fail(function(err) {
+ .fail(function (err) {
assert.ok(err instanceof TException);
});
Q.resolve(client.testException("Xception"))
- .then(function(response) {
+ .then(function (response) {
fail("testException: Xception");
})
- .fail(function(err) {
+ .fail(function (err) {
assert.ok(err instanceof ttypes.Xception);
assert.equal(err.errorCode, 1001);
assert.equal("Xception", err.message);
});
Q.resolve(client.testException("no Exception"))
- .then(function(response) {
+ .then(function (response) {
assert.equal(undefined, response); //void
})
.fail(fail("testException"));
client.testOneway(0, fail("testOneway: should not answer"));
- checkOffByOne(function(done) {
+ checkOffByOne(function (done) {
Q.resolve(client.testI32(-1))
- .then(function(response) {
- assert.equal(-1, response);
- assert.end();
- done();
+ .then(function (response) {
+ assert.equal(-1, response);
+ assert.end();
+ done();
})
.fail(fail("checkOffByOne"));
}, callback);
});
-};
-
+}
// Helper Functions
// =========================================================
function makeRecursiveCheck(assert: test.Test) {
-
return function (map1: any, map2: any, msg: string) {
var equal = true;
@@ -218,30 +229,37 @@
assert.ok(equal, msg);
// deepEqual doesn't work with fields using node-int64
- function checkRecursively(map1: any, map2: any) : boolean {
+ function checkRecursively(map1: any, map2: any): boolean {
if (!(typeof map1 !== "function" && typeof map2 !== "function")) {
return false;
}
if (!map1 || typeof map1 !== "object") {
//Handle int64 types (which use node-int64 in Node.js JavaScript)
- if ((typeof map1 === "number") && (typeof map2 === "object") &&
- (map2.buffer) && (map2.buffer instanceof Buffer) && (map2.buffer.length === 8)) {
+ if (
+ typeof map1 === "number" &&
+ typeof map2 === "object" &&
+ map2.buffer &&
+ map2.buffer instanceof Buffer &&
+ map2.buffer.length === 8
+ ) {
var n = new Int64(map2.buffer);
return map1 === n.toNumber();
} else {
return map1 == map2;
}
} else {
- return Object.keys(map1).every(function(key) {
+ return Object.keys(map1).every(function (key) {
return checkRecursively(map1[key], map2[key]);
});
}
}
- }
+ };
}
-function checkOffByOne(done: (callback: () => void) => void, callback: (message: string) => void) {
-
+function checkOffByOne(
+ done: (callback: () => void) => void,
+ callback: (message: string) => void,
+) {
var retry_limit = 30;
var retry_interval = 100;
var test_complete = false;
@@ -256,20 +274,23 @@
* Because this is the last test against the server, when it completes
* the entire suite is complete by definition (the tests run serially).
*/
- done(function() {
+ done(function () {
test_complete = true;
});
//We wait up to retry_limit * retry_interval for the test suite to complete
function TestForCompletion() {
- if(test_complete && callback) {
+ if (test_complete && callback) {
callback("Server successfully tested!");
} else {
if (++retrys < retry_limit) {
setTimeout(TestForCompletion, retry_interval);
} else if (callback) {
- callback("Server test failed to complete after " +
- (retry_limit * retry_interval / 1000) + " seconds");
+ callback(
+ "Server test failed to complete after " +
+ (retry_limit * retry_interval) / 1000 +
+ " seconds",
+ );
}
}
}
diff --git a/lib/nodets/test/test_handler.ts b/lib/nodets/test/test_handler.ts
index 996c32a..823b4e7 100644
--- a/lib/nodets/test/test_handler.ts
+++ b/lib/nodets/test/test_handler.ts
@@ -26,7 +26,6 @@
import Q = require("q");
import Int64 = require("node-int64");
-
export class SyncThriftTestHandler {
testVoid(): Q.IPromise<void> {
//console.log('testVoid()');
@@ -35,9 +34,9 @@
testMapMap(hello: number) {
//console.log('testMapMap(' + hello + ')');
- var mapmap: {[key: number]: {[key: number]: number; }} = [];
- var pos: {[key: number]: number; } = [];
- var neg: {[key: number]: number; } = [];
+ var mapmap: { [key: number]: { [key: number]: number } } = [];
+ var pos: { [key: number]: number } = [];
+ var neg: { [key: number]: number } = [];
for (var i = 1; i < 5; i++) {
pos[i] = i;
neg[-i] = -i;
@@ -47,53 +46,60 @@
return Q.resolve(mapmap);
}
- testInsanity(argument: ttypes.Insanity): Q.IPromise<{ [k: number]: any; }> {
- const first_map: { [k: number]: any; } = [];
- const second_map: { [k: number]: any; } = [];
-
+ testInsanity(argument: ttypes.Insanity): Q.IPromise<{ [k: number]: any }> {
+ const first_map: { [k: number]: any } = [];
+ const second_map: { [k: number]: any } = [];
+
first_map[ttypes.Numberz.TWO] = argument;
first_map[ttypes.Numberz.THREE] = argument;
-
+
const looney = new ttypes.Insanity();
second_map[ttypes.Numberz.SIX] = looney;
-
- const insane: { [k: number]: any; } = [];
+
+ const insane: { [k: number]: any } = [];
insane[1] = first_map;
insane[2] = second_map;
return Q.resolve(insane);
}
- testMulti(arg0: any, arg1: number, arg2: Int64, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number) {
+ testMulti(
+ arg0: any,
+ arg1: number,
+ arg2: Int64,
+ arg3: { [k: number]: string },
+ arg4: ttypes.Numberz,
+ arg5: number,
+ ) {
var hello = new ttypes.Xtruct();
- hello.string_thing = 'Hello2';
+ hello.string_thing = "Hello2";
hello.byte_thing = arg0;
hello.i32_thing = arg1;
hello.i64_thing = arg2;
return Q.resolve(hello);
}
testException(arg: string): Q.IPromise<void> {
- if (arg === 'Xception') {
+ if (arg === "Xception") {
var x = new ttypes.Xception();
x.errorCode = 1001;
x.message = arg;
throw x;
- } else if (arg === 'TException') {
+ } else if (arg === "TException") {
throw new Thrift.TException(arg);
} else {
return Q.resolve();
}
}
testMultiException(arg0: string, arg1: string) {
- if (arg0 === ('Xception')) {
+ if (arg0 === "Xception") {
var x = new ttypes.Xception();
x.errorCode = 1001;
- x.message = 'This is an Xception';
+ x.message = "This is an Xception";
throw x;
- } else if (arg0 === ('Xception2')) {
+ } else if (arg0 === "Xception2") {
var x2 = new ttypes.Xception2();
x2.errorCode = 2002;
x2.struct_thing = new ttypes.Xtruct();
- x2.struct_thing.string_thing = 'This is an Xception2';
+ x2.struct_thing.string_thing = "This is an Xception2";
throw x2;
}
@@ -101,8 +107,7 @@
res.string_thing = arg1;
return Q.resolve(res);
}
- testOneway(sleepFor: number) {
- }
+ testOneway(sleepFor: number) {}
testString(thing: string) {
return Q.resolve(thing);
@@ -131,10 +136,10 @@
testNest(thing: ttypes.Xtruct2) {
return Q.resolve(thing);
}
- testMap(thing: { [k: number]: number; }) {
+ testMap(thing: { [k: number]: number }) {
return Q.resolve(thing);
}
- testStringMap(thing: { [k: string]: string; }) {
+ testStringMap(thing: { [k: string]: string }) {
return Q.resolve(thing);
}
testSet(thing: number[]) {
@@ -161,13 +166,16 @@
callback(undefined);
return Q.resolve();
}
- testMapMap(hello: number,
- callback: (err: any, result: { [k: number]: { [k: number]: number; }; }) => void):
- Q.IPromise<{ [k: number]: { [k: number]: number; }; }> {
-
- var mapmap: {[key: number]: {[key: number]: number; }} = [];
- var pos: {[key: number]: number; } = [];
- var neg: {[key: number]: number; } = [];
+ testMapMap(
+ hello: number,
+ callback: (
+ err: any,
+ result: { [k: number]: { [k: number]: number } },
+ ) => void,
+ ): Q.IPromise<{ [k: number]: { [k: number]: number } }> {
+ var mapmap: { [key: number]: { [key: number]: number } } = [];
+ var pos: { [key: number]: number } = [];
+ var neg: { [key: number]: number } = [];
for (var i = 1; i < 5; i++) {
pos[i] = i;
neg[-i] = -i;
@@ -178,54 +186,69 @@
callback(null, mapmap);
return Q.resolve();
}
- testInsanity(argument: ttypes.Insanity, callback?: (err: any, result: { [k: number]: any; }) => void): Q.IPromise<{ [k: number]: any; }> {
- const first_map: { [k: number]: any; } = [];
- const second_map: { [k: number]: any; } = [];
-
+ testInsanity(
+ argument: ttypes.Insanity,
+ callback?: (err: any, result: { [k: number]: any }) => void,
+ ): Q.IPromise<{ [k: number]: any }> {
+ const first_map: { [k: number]: any } = [];
+ const second_map: { [k: number]: any } = [];
+
first_map[ttypes.Numberz.TWO] = argument;
first_map[ttypes.Numberz.THREE] = argument;
-
+
const looney = new ttypes.Insanity();
second_map[ttypes.Numberz.SIX] = looney;
-
- const insane: { [k: number]: any; } = [];
+
+ const insane: { [k: number]: any } = [];
insane[1] = first_map;
insane[2] = second_map;
- if (callback !== undefined){
+ if (callback !== undefined) {
callback(null, insane);
}
return Q.resolve();
}
- testMulti(arg0: any, arg1: number, arg2: Int64, arg3: { [k: number]: string; }, arg4: ttypes.Numberz, arg5: number, result: Function): Q.IPromise<ttypes.Xtruct> {
+ testMulti(
+ arg0: any,
+ arg1: number,
+ arg2: Int64,
+ arg3: { [k: number]: string },
+ arg4: ttypes.Numberz,
+ arg5: number,
+ result: Function,
+ ): Q.IPromise<ttypes.Xtruct> {
var hello = this.syncHandler.testMulti(arg0, arg1, arg2, arg3, arg4, arg5);
- hello.then(hello => result(null, hello));
+ hello.then((hello) => result(null, hello));
return Q.resolve();
}
testException(arg: string, result: (err: any) => void): Q.IPromise<void> {
- if (arg === 'Xception') {
+ if (arg === "Xception") {
var x = new ttypes.Xception();
x.errorCode = 1001;
x.message = arg;
result(x);
- } else if (arg === 'TException') {
+ } else if (arg === "TException") {
result(new Thrift.TException(arg));
} else {
result(null);
}
return Q.resolve();
}
- testMultiException(arg0: string, arg1: string, result: (err: any, res?: ttypes.Xtruct) => void): Q.IPromise<ttypes.Xtruct> {
- if (arg0 === ('Xception')) {
+ testMultiException(
+ arg0: string,
+ arg1: string,
+ result: (err: any, res?: ttypes.Xtruct) => void,
+ ): Q.IPromise<ttypes.Xtruct> {
+ if (arg0 === "Xception") {
var x = new ttypes.Xception();
x.errorCode = 1001;
- x.message = 'This is an Xception';
+ x.message = "This is an Xception";
result(x);
- } else if (arg0 === ('Xception2')) {
+ } else if (arg0 === "Xception2") {
var x2 = new ttypes.Xception2();
x2.errorCode = 2002;
x2.struct_thing = new ttypes.Xtruct();
- x2.struct_thing.string_thing = 'This is an Xception2';
+ x2.struct_thing.string_thing = "This is an Xception2";
result(x2);
} else {
var res = new ttypes.Xtruct();
@@ -237,63 +260,108 @@
testOneway(sleepFor: number, result: Function) {
this.syncHandler.testOneway(sleepFor);
}
- testString(thing: string, callback: (err: any, result: string) => void): Q.IPromise<string> {
+ testString(
+ thing: string,
+ callback: (err: any, result: string) => void,
+ ): Q.IPromise<string> {
callback(null, thing);
return Q.resolve();
}
- testByte(thing: number, callback: (err: any, result: number) => void): Q.IPromise<number> {
+ testByte(
+ thing: number,
+ callback: (err: any, result: number) => void,
+ ): Q.IPromise<number> {
callback(null, thing);
return Q.resolve();
}
- testBool(thing: boolean, callback: (err: any, result: boolean) => void ): Q.IPromise<boolean> {
+ testBool(
+ thing: boolean,
+ callback: (err: any, result: boolean) => void,
+ ): Q.IPromise<boolean> {
callback(null, thing);
return Q.resolve();
}
- testI32(thing: number, callback: (err: any, result: number) => void): Q.IPromise<number> {
+ testI32(
+ thing: number,
+ callback: (err: any, result: number) => void,
+ ): Q.IPromise<number> {
callback(null, thing);
return Q.resolve();
}
- testI64(thing: number, callback: (err: any, result: number) => void): Q.IPromise<number> {
+ testI64(
+ thing: number,
+ callback: (err: any, result: number) => void,
+ ): Q.IPromise<number> {
callback(null, thing);
return Q.resolve();
}
- testDouble(thing: number, callback: (err: any, result: number) => void): Q.IPromise<number> {
+ testDouble(
+ thing: number,
+ callback: (err: any, result: number) => void,
+ ): Q.IPromise<number> {
callback(null, thing);
return Q.resolve();
}
- testBinary(thing: Buffer, callback: (err: any, result: Buffer) => void): Q.IPromise<Buffer> {
+ testBinary(
+ thing: Buffer,
+ callback: (err: any, result: Buffer) => void,
+ ): Q.IPromise<Buffer> {
callback(null, thing);
return Q.resolve();
}
- testStruct(thing: ttypes.Xtruct, callback: (err: any, result: ttypes.Xtruct) => void): Q.IPromise<ttypes.Xtruct> {
+ testStruct(
+ thing: ttypes.Xtruct,
+ callback: (err: any, result: ttypes.Xtruct) => void,
+ ): Q.IPromise<ttypes.Xtruct> {
callback(null, thing);
return Q.resolve();
}
- testNest(thing: ttypes.Xtruct2, callback: (err: any, result: ttypes.Xtruct2) => void): Q.IPromise<ttypes.Xtruct2> {
+ testNest(
+ thing: ttypes.Xtruct2,
+ callback: (err: any, result: ttypes.Xtruct2) => void,
+ ): Q.IPromise<ttypes.Xtruct2> {
callback(null, thing);
return Q.resolve();
}
- testMap(thing: { [k: number]: number; }, callback: (err: any, result: { [k: number]: number; }) => void): Q.IPromise<{ [k: number]: number; }> {
+ testMap(
+ thing: { [k: number]: number },
+ callback: (err: any, result: { [k: number]: number }) => void,
+ ): Q.IPromise<{ [k: number]: number }> {
callback(null, thing);
return Q.resolve();
}
- testStringMap(thing: { [k: string]: string; }, callback: (err: any, result: { [k: string]: string; }) => void): Q.IPromise<{ [k: string]: string; }> {
+ testStringMap(
+ thing: { [k: string]: string },
+ callback: (err: any, result: { [k: string]: string }) => void,
+ ): Q.IPromise<{ [k: string]: string }> {
callback(null, thing);
return Q.resolve();
}
- testSet(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise<number[]> {
+ testSet(
+ thing: number[],
+ callback: (err: any, result: number[]) => void,
+ ): Q.IPromise<number[]> {
callback(null, thing);
return Q.resolve();
}
- testList(thing: number[], callback: (err: any, result: number[]) => void): Q.IPromise<number[]> {
+ testList(
+ thing: number[],
+ callback: (err: any, result: number[]) => void,
+ ): Q.IPromise<number[]> {
callback(null, thing);
return Q.resolve();
}
- testEnum(thing: ttypes.Numberz, callback: (err: any, result: ttypes.Numberz) => void): Q.IPromise<ttypes.Numberz> {
+ testEnum(
+ thing: ttypes.Numberz,
+ callback: (err: any, result: ttypes.Numberz) => void,
+ ): Q.IPromise<ttypes.Numberz> {
callback(null, thing);
return Q.resolve();
}
- testTypedef(thing: number, callback: (err: any, result: number) => void): Q.IPromise<number> {
+ testTypedef(
+ thing: number,
+ callback: (err: any, result: number) => void,
+ ): Q.IPromise<number> {
callback(null, thing);
return Q.resolve();
}
diff --git a/lib/ts/Gruntfile.js b/lib/ts/Gruntfile.js
index 61ab582..3e4b1c4 100644
--- a/lib/ts/Gruntfile.js
+++ b/lib/ts/Gruntfile.js
@@ -5,55 +5,57 @@
// Grunt Setup - npm install //reads the ./package.json and installs project dependencies
// Run grunt - npx grunt // uses project-local installed version of grunt (from package.json)
-module.exports = function(grunt) {
- 'use strict';
+module.exports = function (grunt) {
+ "use strict";
grunt.initConfig({
- pkg: grunt.file.readJSON('package.json'),
+ pkg: grunt.file.readJSON("package.json"),
concat: {
options: {
- separator: ';'
+ separator: ";",
},
dist: {
- src: ['src/**/*.js'],
- dest: 'dist/<%= pkg.name %>.js'
- }
+ src: ["src/**/*.js"],
+ dest: "dist/<%= pkg.name %>.js",
+ },
},
shell: {
InstallThriftJS: {
- command: 'mkdir -p test/build/ts/lib; cp ../js/src/thrift.js test/build/ts/thrift.js'
+ command:
+ "mkdir -p test/build/ts/lib; cp ../js/src/thrift.js test/build/ts/thrift.js",
},
InstallThriftNodeJSDep: {
- command: 'cd ../..; npm install'
+ command: "cd ../..; npm install",
},
InstallTestLibs: {
- command: 'cd test; ant download_jslibs'
+ command: "cd test; ant download_jslibs",
},
ThriftGen: {
command: [
- 'mkdir -p test/gen-js',
- '../../compiler/cpp/thrift -gen js:ts --out test/gen-js ../../test/v0.16/ThriftTest.thrift',
- 'mkdir -p test/gen-nodejs',
- '../../compiler/cpp/thrift -gen js:node,ts --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift',
- ].join(' && ')
+ "mkdir -p test/gen-js",
+ "../../compiler/cpp/thrift -gen js:ts --out test/gen-js ../../test/v0.16/ThriftTest.thrift",
+ "mkdir -p test/gen-nodejs",
+ "../../compiler/cpp/thrift -gen js:node,ts --out test/gen-nodejs ../../test/v0.16/ThriftTest.thrift",
+ ].join(" && "),
},
ThriftBrowserifyNodeInt64: {
command: [
- './node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js',
- './node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js',
- './node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js'
- ].join(' && ')
+ "./node_modules/browserify/bin/cmd.js ./node_modules/node-int64/Int64.js -s Int64 -o test/build/js/lib/Int64.js",
+ "./node_modules/browserify/bin/cmd.js ../nodejs/lib/thrift/int64_util.js -s Int64Util -o test/build/js/lib/Int64Util.js",
+ "./node_modules/browserify/bin/cmd.js ./node_modules/json-int64/index.js -s JSONInt64 -o test/build/js/lib/JSONInt64.js",
+ ].join(" && "),
},
ThriftGenInt64: {
- command: '../../compiler/cpp/thrift -gen js:ts -o test ../../test/Int64Test.thrift'
+ command:
+ "../../compiler/cpp/thrift -gen js:ts -o test ../../test/Int64Test.thrift",
},
ThriftTestServer: {
options: {
async: true,
execOptions: {
cwd: "./test",
- env: {NODE_PATH: "../../nodejs/lib:../../../node_modules"}
- }
+ env: { NODE_PATH: "../../nodejs/lib:../../../node_modules" },
+ },
},
command: "node server_http.js",
},
@@ -61,103 +63,104 @@
options: {
execOptions: {
cwd: "./test",
- }
+ },
},
- command : "../node_modules/typescript/bin/tsc --listFiles --outDir build/ts"
+ command:
+ "../node_modules/typescript/bin/tsc --listFiles --outDir build/ts",
},
BrowserifyCompiledTS: {
command: [
"./node_modules/browserify/bin/cmd.js test/build/ts/test.js -o test/build/ts/lib/test.js --standalone test",
"./node_modules/browserify/bin/cmd.js test/build/ts/test-int64.js -o test/build/ts/lib/test-int64.js --standalone testInt64",
- ].join(" && ")
+ ].join(" && "),
},
InstallGeneratedCode: {
command: [
"mkdir -p test/build/ts",
- "cp -r test/gen-js test/build/ts"
- ].join(" && ")
+ "cp -r test/gen-js test/build/ts",
+ ].join(" && "),
},
},
qunit: {
ThriftJS: {
options: {
- urls: [
- 'http://localhost:8089/test.html'
- ],
+ urls: ["http://localhost:8089/test.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
},
- }
+ },
},
ThriftJS_Int64: {
options: {
- urls: [
- 'http://localhost:8089/test-int64.html'
- ],
+ urls: ["http://localhost:8089/test-int64.html"],
puppeteer: {
headless: true,
- args: ['--no-sandbox'],
+ args: ["--no-sandbox"],
ignoreHTTPSErrors: true,
},
- }
+ },
},
},
jshint: {
// The main Thrift library file. not es6 yet :(
lib: {
- src: ['../js/src/**/*.js'],
+ src: ["../js/src/**/*.js"],
},
// The test files use es6
test: {
- src: ['Gruntfile.js', 'test/*.js'],
+ src: ["Gruntfile.js", "test/*.js"],
options: {
esversion: 6,
- }
+ },
},
gen_js_code: {
- src: ['test/gen-js/*.js'],
+ src: ["test/gen-js/*.js"],
},
gen_node_code: {
- src: ['test/gen-nodejs/*.js'],
+ src: ["test/gen-nodejs/*.js"],
options: {
node: true,
- }
+ },
},
},
});
- grunt.loadNpmTasks('grunt-contrib-jshint');
- grunt.loadNpmTasks('grunt-contrib-qunit');
- grunt.loadNpmTasks('grunt-shell-spawn');
+ grunt.loadNpmTasks("grunt-contrib-jshint");
+ grunt.loadNpmTasks("grunt-contrib-qunit");
+ grunt.loadNpmTasks("grunt-shell-spawn");
- grunt.registerTask('wait', 'Wait just one second for the server to start', function () {
- var done = this.async();
- setTimeout(function() {
- done(true);
- }, 1000);
- });
+ grunt.registerTask(
+ "wait",
+ "Wait just one second for the server to start",
+ function () {
+ var done = this.async();
+ setTimeout(function () {
+ done(true);
+ }, 1000);
+ },
+ );
- grunt.registerTask('installAndGenerate', [
- 'shell:InstallThriftJS',
- 'shell:InstallThriftNodeJSDep',
- 'shell:ThriftGen',
- 'shell:ThriftBrowserifyNodeInt64',
- 'shell:ThriftGenInt64',
- 'shell:InstallTestLibs',
- 'shell:BuildTS',
- 'shell:InstallGeneratedCode',
- 'shell:BrowserifyCompiledTS',
+ grunt.registerTask("installAndGenerate", [
+ "shell:InstallThriftJS",
+ "shell:InstallThriftNodeJSDep",
+ "shell:ThriftGen",
+ "shell:ThriftBrowserifyNodeInt64",
+ "shell:ThriftGenInt64",
+ "shell:InstallTestLibs",
+ "shell:BuildTS",
+ "shell:InstallGeneratedCode",
+ "shell:BrowserifyCompiledTS",
]);
- grunt.registerTask('test', [
- 'installAndGenerate',
- 'jshint',
- 'shell:ThriftTestServer',
- 'wait',
- 'qunit:ThriftJS',
- 'qunit:ThriftJS_Int64',
- 'shell:ThriftTestServer:kill',
+ grunt.registerTask("test", [
+ "installAndGenerate",
+ "jshint",
+ "shell:ThriftTestServer",
+ "wait",
+ "qunit:ThriftJS",
+ "qunit:ThriftJS_Int64",
+ "shell:ThriftTestServer:kill",
]);
- grunt.registerTask('default', ['test']);
+ grunt.registerTask("default", ["test"]);
};
diff --git a/lib/ts/test/phantom-client.ts b/lib/ts/test/phantom-client.ts
index 5518937..90a532d 100644
--- a/lib/ts/test/phantom-client.ts
+++ b/lib/ts/test/phantom-client.ts
@@ -16,337 +16,360 @@
* specific language governing permissions and limitations
* under the License.
*/
- /* jshint -W100 */
+/* jshint -W100 */
import { ThriftTest } from "./gen-js/ThriftTest_types";
import "./gen-js/ThriftTest";
var Int64 = require("node-int64");
var phantom = require("phantom");
-const int64_2_pow_60: typeof Int64 = new Int64('1000000000000000');
-const int64_minus_2_pow_60: typeof Int64 = new Int64('f000000000000000');
+const int64_2_pow_60: typeof Int64 = new Int64("1000000000000000");
+const int64_minus_2_pow_60: typeof Int64 = new Int64("f000000000000000");
- (function() {
- 'use strict';
-
- // Rudimentary test helper functions
- // TODO: Return error code based on kind of errors rather than throw
- var ok = function(t, msg) {
- if (!t) {
- console.log('*** FAILED ***');
- throw new Error(msg);
+(function () {
+ "use strict";
+
+ // Rudimentary test helper functions
+ // TODO: Return error code based on kind of errors rather than throw
+ var ok = function (t, msg) {
+ if (!t) {
+ console.log("*** FAILED ***");
+ throw new Error(msg);
+ }
+ };
+ var equal = function (a, b) {
+ if (a !== b) {
+ console.log("*** FAILED ***");
+ throw new Error();
+ }
+ };
+ var test = function (name, f) {
+ console.log("TEST : " + name);
+ f();
+ console.log("OK\n");
+ };
+
+ var parseArgs = function (args) {
+ var skips = ["--transport=http", "--protocol=json"];
+ var opts = {
+ port: "9090",
+ // protocol: 'json',
+ };
+ var keys = {};
+ for (var key in opts) {
+ keys["--" + key + "="] = key;
+ }
+ for (var i in args) {
+ var arg = args[i];
+ if (skips.indexOf(arg) != -1) {
+ continue;
}
- };
- var equal = function(a, b) {
- if (a !== b) {
- console.log('*** FAILED ***');
- throw new Error();
+ var hit = false;
+ for (var k in keys) {
+ if (arg.slice(0, k.length) === k) {
+ opts[keys[k]] = arg.slice(k.length);
+ hit = true;
+ break;
+ }
}
- };
- var test = function(name, f) {
- console.log('TEST : ' + name);
- f();
- console.log('OK\n');
- };
-
- var parseArgs = function(args) {
- var skips = [
- '--transport=http',
- '--protocol=json'
- ];
- var opts = {
- port: '9090'
- // protocol: 'json',
+ if (!hit) {
+ throw new Error("Unknown argument: " + arg);
+ }
+ }
+ var portAsInt: number = parseInt(opts.port, 10);
+ if (!opts.port || portAsInt < 1 || portAsInt > 65535) {
+ throw new Error("Invalid port number");
+ }
+ return opts;
+ };
+
+ var execute = function () {
+ console.log("### Apache Thrift Javascript standalone test client");
+ console.log("------------------------------------------------------------");
+
+ phantom.page.injectJs("thrift.js");
+ phantom.page.injectJs("gen-js/ThriftTest_types.js");
+ phantom.page.injectJs("gen-js/ThriftTest.js");
+
+ var system = require("system");
+ var opts = parseArgs(system.args.slice(1));
+ var port = opts.port;
+ var transport = new Thrift.Transport(
+ "http://localhost:" + port + "/service",
+ );
+ var protocol = new Thrift.Protocol(transport);
+ var client = new ThriftTest.ThriftTestClient(protocol);
+
+ // TODO: Remove duplicate code with test.js.
+ // all Languages in UTF-8
+ var stringTest =
+ "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語";
+
+ function checkRecursively(map1, map2) {
+ if (typeof map1 !== "function" && typeof map2 !== "function") {
+ if (!map1 || typeof map1 !== "object") {
+ equal(map1, map2);
+ } else {
+ for (var key in map1) {
+ checkRecursively(map1[key], map2[key]);
+ }
+ }
+ }
+ }
+
+ test("Void", function () {
+ equal(client.testVoid(), undefined);
+ });
+ test("Binary (String)", function () {
+ var binary: string = "";
+ for (var v = 255; v >= 0; --v) {
+ binary += String.fromCharCode(v);
+ }
+ equal(client.testBinary(binary), binary);
+ });
+ test("Binary (Uint8Array)", function () {
+ var binary: string = "";
+ for (var v = 255; v >= 0; --v) {
+ binary += String.fromCharCode(v);
+ }
+ var arr = new Uint8Array(binary.length);
+ for (var i = 0; i < binary.length; ++i) {
+ arr[i] = binary[i].charCodeAt(0);
+ }
+ const hexEncodedString = Array.from(arr, function (byte) {
+ return String.fromCharCode(byte);
+ }).join("");
+ equal(client.testBinary(hexEncodedString), binary);
+ });
+ test("String", function () {
+ equal(client.testString(""), "");
+ equal(client.testString(stringTest), stringTest);
+
+ var specialCharacters =
+ 'quote: \" backslash:' +
+ " forwardslash-escaped: \/ " +
+ " backspace: \b formfeed: \f newline: \n return: \r tab: " +
+ ' now-all-of-them-together: "\\\/\b\n\r\t' +
+ " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><";
+ equal(client.testString(specialCharacters), specialCharacters);
+ });
+ test("Double", function () {
+ equal(client.testDouble(0), 0);
+ equal(client.testDouble(-1), -1);
+ equal(client.testDouble(3.14), 3.14);
+ equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60));
+ });
+ test("Bool", function () {
+ equal(client.testBool(true), true);
+ equal(client.testBool(false), false);
+ });
+ test("I8", function () {
+ equal(client.testByte(0), 0);
+ equal(client.testByte(0x01), 0x01);
+ });
+ test("I32", function () {
+ equal(client.testI32(0), 0);
+ equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30));
+ equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30));
+ });
+ test("I64", function () {
+ equal(client.testI64(new Int64(0)), 0);
+ equal(client.testI64(int64_2_pow_60), Math.pow(2, 52));
+ equal(client.testI64(int64_minus_2_pow_60), -Math.pow(2, 52));
+ });
+
+ test("Struct", function () {
+ var structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
+ structTestInput.string_thing = "worked";
+ structTestInput.byte_thing = 0x01;
+ structTestInput.i32_thing = Math.pow(2, 30);
+ structTestInput.i64_thing = int64_2_pow_60;
+
+ var structTestOutput: ThriftTest.Xtruct =
+ client.testStruct(structTestInput);
+
+ equal(structTestOutput.string_thing, structTestInput.string_thing);
+ equal(structTestOutput.byte_thing, structTestInput.byte_thing);
+ equal(structTestOutput.i32_thing, structTestInput.i32_thing);
+ equal(structTestOutput.i64_thing, structTestInput.i64_thing);
+
+ equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
+ });
+
+ test("Nest", function () {
+ var xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
+ xtrTestInput.string_thing = "worked";
+ xtrTestInput.byte_thing = 0x01;
+ xtrTestInput.i32_thing = Math.pow(2, 30);
+ xtrTestInput.i64_thing = int64_2_pow_60;
+
+ var nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2();
+ nestTestInput.byte_thing = 0x02;
+ nestTestInput.struct_thing = xtrTestInput;
+ nestTestInput.i32_thing = Math.pow(2, 15);
+
+ var nestTestOutput = client.testNest(nestTestInput);
+
+ equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
+ equal(
+ nestTestOutput.struct_thing.string_thing,
+ nestTestInput.struct_thing.string_thing,
+ );
+ equal(
+ nestTestOutput.struct_thing.byte_thing,
+ nestTestInput.struct_thing.byte_thing,
+ );
+ equal(
+ nestTestOutput.struct_thing.i32_thing,
+ nestTestInput.struct_thing.i32_thing,
+ );
+ equal(
+ nestTestOutput.struct_thing.i64_thing,
+ nestTestInput.struct_thing.i64_thing,
+ );
+ equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
+
+ equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
+ });
+
+ test("Map", function () {
+ var mapTestInput: { [k: number]: number } = { 7: 77, 8: 88, 9: 99 };
+
+ var mapTestOutput: { [k: number]: number } = client.testMap(mapTestInput);
+
+ for (var key in mapTestOutput) {
+ equal(mapTestOutput[key], mapTestInput[key]);
+ }
+ });
+
+ test("StringMap", function () {
+ var mapTestInput: { [k: string]: string } = {
+ a: "123",
+ "a b": "with spaces ",
+ same: "same",
+ "0": "numeric key",
+ longValue: stringTest,
+ stringTest: "long key",
};
- var keys = {};
- for (var key in opts) {
- keys['--' + key + '='] = key;
+
+ var mapTestOutput: { [k: string]: string } =
+ client.testStringMap(mapTestInput);
+
+ for (var key in mapTestOutput) {
+ equal(mapTestOutput[key], mapTestInput[key]);
}
- for (var i in args) {
- var arg = args[i];
- if (skips.indexOf(arg) != -1) {
- continue;
- }
- var hit = false;
- for (var k in keys) {
- if (arg.slice(0, k.length) === k) {
- opts[keys[k]] = arg.slice(k.length);
- hit = true;
- break;
- }
- }
- if (!hit) {
- throw new Error('Unknown argument: ' + arg);
+ });
+
+ test("Set", function () {
+ var setTestInput: number[] = [1, 2, 3];
+ ok(client.testSet(setTestInput), setTestInput);
+ });
+
+ test("List", function () {
+ var listTestInput: number[] = [1, 2, 3];
+ ok(client.testList(listTestInput), listTestInput);
+ });
+
+ test("Enum", function () {
+ equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
+ });
+
+ test("TypeDef", function () {
+ equal(client.testTypedef(new Int64(69)), 69);
+ });
+
+ test("MapMap", function () {
+ var mapMapTestExpectedResult: { [K: number]: { [k: number]: number } } = {
+ "4": { "1": 1, "2": 2, "3": 3, "4": 4 },
+ "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 },
+ };
+
+ var mapMapTestOutput = client.testMapMap(1);
+
+ for (var key in mapMapTestOutput) {
+ for (var key2 in mapMapTestOutput[key]) {
+ equal(
+ mapMapTestOutput[key][key2],
+ mapMapTestExpectedResult[key][key2],
+ );
}
}
- var portAsInt: number = parseInt(opts.port, 10);
- if (!opts.port || portAsInt < 1 || portAsInt > 65535) {
- throw new Error('Invalid port number');
+
+ checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
+ });
+
+ test("Xception", function () {
+ try {
+ client.testException("Xception");
+ ok(false, "expected an exception but there was no exception");
+ } catch (e) {
+ equal(e.errorCode, 1001);
+ equal(e.message, "Xception");
}
- return opts;
- };
-
- var execute = function() {
- console.log('### Apache Thrift Javascript standalone test client');
- console.log('------------------------------------------------------------');
-
- phantom.page.injectJs('thrift.js');
- phantom.page.injectJs('gen-js/ThriftTest_types.js');
- phantom.page.injectJs('gen-js/ThriftTest.js');
-
- var system = require('system');
- var opts = parseArgs(system.args.slice(1));
- var port = opts.port;
- var transport = new Thrift.Transport('http://localhost:' + port + '/service');
- var protocol = new Thrift.Protocol(transport);
- var client = new ThriftTest.ThriftTestClient(protocol);
-
-
- // TODO: Remove duplicate code with test.js.
- // all Languages in UTF-8
- var stringTest = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語";
-
- function checkRecursively(map1, map2) {
- if (typeof map1 !== 'function' && typeof map2 !== 'function') {
- if (!map1 || typeof map1 !== 'object') {
- equal(map1, map2);
- } else {
- for (var key in map1) {
- checkRecursively(map1[key], map2[key]);
- }
- }
- }
+ });
+
+ test("no Exception", function () {
+ try {
+ client.testException("no Exception");
+ } catch (e) {
+ ok(false, "expected no exception but here was an exception");
}
-
- test('Void', function() {
- equal(client.testVoid(), undefined);
- });
- test('Binary (String)', function() {
- var binary: string = '';
- for (var v = 255; v >= 0; --v) {
- binary += String.fromCharCode(v);
- }
- equal(client.testBinary(binary), binary);
- });
- test('Binary (Uint8Array)', function() {
- var binary: string = '';
- for (var v = 255; v >= 0; --v) {
- binary += String.fromCharCode(v);
- }
- var arr = new Uint8Array(binary.length);
- for (var i = 0; i < binary.length; ++i) {
- arr[i] = binary[i].charCodeAt(0);
- }
- const hexEncodedString = Array.from(arr, function(byte) {
- return String.fromCharCode(byte);
- }).join('')
- equal(client.testBinary(hexEncodedString), binary);
- });
- test('String', function() {
- equal(client.testString(''), '');
- equal(client.testString(stringTest), stringTest);
-
- var specialCharacters = 'quote: \" backslash:' +
- ' forwardslash-escaped: \/ ' +
- ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
- ' now-all-of-them-together: "\\\/\b\n\r\t' +
- ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
- equal(client.testString(specialCharacters), specialCharacters);
- });
- test('Double', function() {
- equal(client.testDouble(0), 0);
- equal(client.testDouble(-1), -1);
- equal(client.testDouble(3.14), 3.14);
- equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60));
- });
- test('Bool', function() {
- equal(client.testBool(true), true);
- equal(client.testBool(false), false);
- });
- test('I8', function() {
- equal(client.testByte(0), 0);
- equal(client.testByte(0x01), 0x01);
- });
- test('I32', function() {
- equal(client.testI32(0), 0);
- equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30));
- equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30));
- });
- test('I64', function() {
- equal(client.testI64(new Int64(0)), 0);
- equal(client.testI64(int64_2_pow_60), Math.pow(2, 52));
- equal(client.testI64(int64_minus_2_pow_60), -Math.pow(2, 52));
- });
-
- test('Struct', function() {
- var structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
- structTestInput.string_thing = 'worked';
- structTestInput.byte_thing = 0x01;
- structTestInput.i32_thing = Math.pow(2, 30);
- structTestInput.i64_thing = int64_2_pow_60;
-
- var structTestOutput: ThriftTest.Xtruct = client.testStruct(structTestInput);
-
- equal(structTestOutput.string_thing, structTestInput.string_thing);
- equal(structTestOutput.byte_thing, structTestInput.byte_thing);
- equal(structTestOutput.i32_thing, structTestInput.i32_thing);
- equal(structTestOutput.i64_thing, structTestInput.i64_thing);
-
- equal(JSON.stringify(structTestOutput), JSON.stringify(structTestInput));
- });
-
- test('Nest', function() {
- var xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
- xtrTestInput.string_thing = 'worked';
- xtrTestInput.byte_thing = 0x01;
- xtrTestInput.i32_thing = Math.pow(2, 30);
- xtrTestInput.i64_thing = int64_2_pow_60;
-
- var nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2();
- nestTestInput.byte_thing = 0x02;
- nestTestInput.struct_thing = xtrTestInput;
- nestTestInput.i32_thing = Math.pow(2, 15);
-
- var nestTestOutput = client.testNest(nestTestInput);
-
- equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
- equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
- equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
- equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
- equal(nestTestOutput.struct_thing.i64_thing, nestTestInput.struct_thing.i64_thing);
- equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
-
- equal(JSON.stringify(nestTestOutput), JSON.stringify(nestTestInput));
- });
-
- test('Map', function() {
- var mapTestInput: {[k: number]: number;} = {7: 77, 8: 88, 9: 99};
-
- var mapTestOutput: {[k: number]: number;} = client.testMap(mapTestInput);
-
- for (var key in mapTestOutput) {
- equal(mapTestOutput[key], mapTestInput[key]);
- }
- });
-
- test('StringMap', function() {
- var mapTestInput: {[k: string]: string;} = {
- 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key',
- 'longValue': stringTest, stringTest: 'long key'
- };
-
- var mapTestOutput: {[k: string]: string;} = client.testStringMap(mapTestInput);
-
- for (var key in mapTestOutput) {
- equal(mapTestOutput[key], mapTestInput[key]);
- }
- });
-
- test('Set', function() {
- var setTestInput: number[] = [1, 2, 3];
- ok(client.testSet(setTestInput), setTestInput);
- });
-
- test('List', function() {
- var listTestInput: number[] = [1, 2, 3];
- ok(client.testList(listTestInput), listTestInput);
- });
-
- test('Enum', function() {
- equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
- });
-
- test('TypeDef', function() {
- equal(client.testTypedef(new Int64(69)), 69);
- });
-
- test('MapMap', function() {
- var mapMapTestExpectedResult: {[K: number]: {[k: number]: number}} = {
- '4': {'1': 1, '2': 2, '3': 3, '4': 4},
- '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1}
- };
-
- var mapMapTestOutput = client.testMapMap(1);
-
-
- for (var key in mapMapTestOutput) {
- for (var key2 in mapMapTestOutput[key]) {
- equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
- }
- }
-
- checkRecursively(mapMapTestOutput, mapMapTestExpectedResult);
- });
-
- test('Xception', function() {
- try {
- client.testException('Xception');
- ok(false, "expected an exception but there was no exception");
- } catch (e) {
- equal(e.errorCode, 1001);
- equal(e.message, 'Xception');
- }
- });
-
- test('no Exception', function() {
- try {
- client.testException('no Exception');
- } catch (e) {
- ok(false, "expected no exception but here was an exception");
- }
- });
-
- test('TException', function() {
- try {
- client.testException('TException');
- ok(false, "expected an exception but there was no exception");
- } catch (e) {
- ok(ok, "succesfully got exception");
- }
- });
-
- const crazy: ThriftTest.Insanity = {
- 'userMap': { '5': new Int64(5), '8': new Int64(8) },
- 'xtructs': [{
- 'string_thing': 'Goodbye4',
- 'byte_thing': 4,
- 'i32_thing': 4,
- 'i64_thing': new Int64(4)
+ });
+
+ test("TException", function () {
+ try {
+ client.testException("TException");
+ ok(false, "expected an exception but there was no exception");
+ } catch (e) {
+ ok(ok, "succesfully got exception");
+ }
+ });
+
+ const crazy: ThriftTest.Insanity = {
+ userMap: { "5": new Int64(5), "8": new Int64(8) },
+ xtructs: [
+ {
+ string_thing: "Goodbye4",
+ byte_thing: 4,
+ i32_thing: 4,
+ i64_thing: new Int64(4),
},
{
- 'string_thing': 'Hello2',
- 'byte_thing': 2,
- 'i32_thing': 2,
- 'i64_thing': new Int64(2)
- }]
+ string_thing: "Hello2",
+ byte_thing: 2,
+ i32_thing: 2,
+ i64_thing: new Int64(2),
+ },
+ ],
};
- test('Insanity', function() {
- const insanity: {[k: number]: (ThriftTest.Insanity | {[k:number]: ThriftTest.Insanity})} = {
- '1': {
- '2': crazy,
- '3': crazy
- },
- '2': { '6': new ThriftTest.Insanity() }
- };
- var res = client.testInsanity(new ThriftTest.Insanity(crazy));
- ok(res, JSON.stringify(res));
- ok(insanity, JSON.stringify(insanity));
-
- checkRecursively(res, insanity);
- });
-
- console.log('------------------------------------------------------------');
- console.log('### All tests succeeded.');
- return 0;
- };
-
- try {
- var ret = execute();
- phantom.exit(ret);
- } catch (err) {
- // Catch all and exit to avoid hang.
- console.error(err);
- phantom.exit(1);
- }
- })();
-
\ No newline at end of file
+ test("Insanity", function () {
+ const insanity: {
+ [k: number]: ThriftTest.Insanity | { [k: number]: ThriftTest.Insanity };
+ } = {
+ "1": {
+ "2": crazy,
+ "3": crazy,
+ },
+ "2": { "6": new ThriftTest.Insanity() },
+ };
+ var res = client.testInsanity(new ThriftTest.Insanity(crazy));
+ ok(res, JSON.stringify(res));
+ ok(insanity, JSON.stringify(insanity));
+
+ checkRecursively(res, insanity);
+ });
+
+ console.log("------------------------------------------------------------");
+ console.log("### All tests succeeded.");
+ return 0;
+ };
+
+ try {
+ var ret = execute();
+ phantom.exit(ret);
+ } catch (err) {
+ // Catch all and exit to avoid hang.
+ console.error(err);
+ phantom.exit(1);
+ }
+})();
diff --git a/lib/ts/test/server_http.js b/lib/ts/test/server_http.js
index 8380c3a..662a0a7 100644
--- a/lib/ts/test/server_http.js
+++ b/lib/ts/test/server_http.js
@@ -28,28 +28,30 @@
// for the es6 environment or for pre-es6 environment.
//
-const thrift = require('../../nodejs/lib/thrift');
-const es6Mode = process.argv.includes('--es6');
-const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs';
+const thrift = require("../../nodejs/lib/thrift");
+const es6Mode = process.argv.includes("--es6");
+const genFolder = es6Mode ? "gen-nodejs-es6" : "gen-nodejs";
const ThriftTestSvc = require(`./${genFolder}/ThriftTest.js`);
-const ThriftTestHandler = require('./test_handler').ThriftTestHandler;
+const ThriftTestHandler = require("./test_handler").ThriftTestHandler;
const ThriftTestSvcOpt = {
- transport: thrift.TBufferedTransport,
- protocol: thrift.TJSONProtocol,
- processor: ThriftTestSvc,
- handler: ThriftTestHandler
+ transport: thrift.TBufferedTransport,
+ protocol: thrift.TJSONProtocol,
+ processor: ThriftTestSvc,
+ handler: ThriftTestHandler,
};
const ThriftWebServerOptions = {
- files: __dirname,
- services: {
- '/service': ThriftTestSvcOpt
- }
+ files: __dirname,
+ services: {
+ "/service": ThriftTestSvcOpt,
+ },
};
const server = thrift.createWebServer(ThriftWebServerOptions);
const port = es6Mode ? 8088 : 8089;
server.listen(port);
console.log(`Serving files from: ${__dirname}`);
-console.log(`Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`);
+console.log(
+ `Http/Thrift Server (ES6 mode ${es6Mode}) running on port: ${port}`,
+);
diff --git a/lib/ts/test/test-int64.ts b/lib/ts/test/test-int64.ts
index 254d8d7..10e5946 100644
--- a/lib/ts/test/test-int64.ts
+++ b/lib/ts/test/test-int64.ts
@@ -16,86 +16,90 @@
* specific language governing permissions and limitations
* under the License.
*/
- /* jshint -W100 */
+/* jshint -W100 */
var Int64 = require("node-int64");
var JSONInt64 = require("json-int64");
import { Int64Test } from "./gen-js/Int64Test_types";
-
// Work around for old API used by QUnitAdapter of jsTestDriver
-if (typeof QUnit.log == 'function') {
+if (typeof QUnit.log == "function") {
// When using real QUnit (fron PhantomJS) log failures to console
- QUnit.log(function(details) {
+ QUnit.log(function (details) {
if (!details.result) {
- console.log('======== FAIL ========');
- console.log('TestName: ' + details.name);
+ console.log("======== FAIL ========");
+ console.log("TestName: " + details.name);
if (details.message) console.log(details.message);
- console.log('Expected: ' + details.expected);
- console.log('Actual : ' + details.actual);
- console.log('======================');
+ console.log("Expected: " + details.expected);
+ console.log("Actual : " + details.actual);
+ console.log("======================");
}
});
}
-QUnit.module('Int64');
+QUnit.module("Int64");
- QUnit.test('Int64', function(assert) {
- console.log('Int64 test -- starts');
- const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42;
- const EXPECTED_SMALL_INT64: typeof Int64 = new Int64(42);
- const EXPECTED_MAX_JS_SAFE_INT64: typeof Int64 = new Int64(Number.MAX_SAFE_INTEGER);
- const EXPECTED_MIN_JS_SAFE_INT64: typeof Int64 = new Int64(Number.MIN_SAFE_INTEGER);
- const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: typeof Int64 = new Int64("0020000000000000"); // hex-encoded
- const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: typeof Int64 = new Int64("ffe0000000000000"); // hex-encoded 2's complement
- const EXPECTED_MAX_SIGNED_INT64: typeof Int64 = new Int64("7fffffffffffffff"); // hex-encoded
- const EXPECTED_MIN_SIGNED_INT64: typeof Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement
- const EXPECTED_INT64_LIST = [
- EXPECTED_SMALL_INT64,
- EXPECTED_MAX_JS_SAFE_INT64,
- EXPECTED_MIN_JS_SAFE_INT64,
- EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64,
- EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64,
- EXPECTED_MAX_SIGNED_INT64,
- EXPECTED_MIN_SIGNED_INT64
- ];
- assert.ok(EXPECTED_SMALL_INT64.equals(Int64Test.SMALL_INT64));
- assert.ok(EXPECTED_MAX_JS_SAFE_INT64.equals(Int64Test.MAX_JS_SAFE_INT64));
- assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(Int64Test.MIN_JS_SAFE_INT64));
+QUnit.test("Int64", function (assert) {
+ console.log("Int64 test -- starts");
+ const EXPECTED_SMALL_INT64_AS_NUMBER: number = 42;
+ const EXPECTED_SMALL_INT64: typeof Int64 = new Int64(42);
+ const EXPECTED_MAX_JS_SAFE_INT64: typeof Int64 = new Int64(
+ Number.MAX_SAFE_INTEGER,
+ );
+ const EXPECTED_MIN_JS_SAFE_INT64: typeof Int64 = new Int64(
+ Number.MIN_SAFE_INTEGER,
+ );
+ const EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64: typeof Int64 = new Int64(
+ "0020000000000000",
+ ); // hex-encoded
+ const EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64: typeof Int64 = new Int64(
+ "ffe0000000000000",
+ ); // hex-encoded 2's complement
+ const EXPECTED_MAX_SIGNED_INT64: typeof Int64 = new Int64("7fffffffffffffff"); // hex-encoded
+ const EXPECTED_MIN_SIGNED_INT64: typeof Int64 = new Int64("8000000000000000"); // hex-encoded 2's complement
+ const EXPECTED_INT64_LIST = [
+ EXPECTED_SMALL_INT64,
+ EXPECTED_MAX_JS_SAFE_INT64,
+ EXPECTED_MIN_JS_SAFE_INT64,
+ EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64,
+ EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64,
+ EXPECTED_MAX_SIGNED_INT64,
+ EXPECTED_MIN_SIGNED_INT64,
+ ];
+ assert.ok(EXPECTED_SMALL_INT64.equals(Int64Test.SMALL_INT64));
+ assert.ok(EXPECTED_MAX_JS_SAFE_INT64.equals(Int64Test.MAX_JS_SAFE_INT64));
+ assert.ok(EXPECTED_MIN_JS_SAFE_INT64.equals(Int64Test.MIN_JS_SAFE_INT64));
+ assert.ok(
+ EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals(
+ Int64Test.MAX_JS_SAFE_PLUS_ONE_INT64,
+ ),
+ );
+ assert.ok(
+ EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals(
+ Int64Test.MIN_JS_SAFE_MINUS_ONE_INT64,
+ ),
+ );
+ assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(Int64Test.MAX_SIGNED_INT64));
+ assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(Int64Test.MIN_SIGNED_INT64));
+ assert.equal(
+ EXPECTED_SMALL_INT64_AS_NUMBER,
+ Int64Test.SMALL_INT64.toNumber(),
+ );
+ assert.equal(Number.MAX_SAFE_INTEGER, Int64Test.MAX_JS_SAFE_INT64.toNumber());
+ assert.equal(Number.MIN_SAFE_INTEGER, Int64Test.MIN_JS_SAFE_INT64.toNumber());
+
+ for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
+ assert.ok(EXPECTED_INT64_LIST[i].equals(Int64Test.INT64_LIST[i]));
+ }
+
+ for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
+ let int64Object = EXPECTED_INT64_LIST[i];
assert.ok(
- EXPECTED_MAX_JS_SAFE_PLUS_ONE_INT64.equals(
- Int64Test.MAX_JS_SAFE_PLUS_ONE_INT64
- )
+ Int64Test.INT64_2_INT64_MAP[
+ JSONInt64.toDecimalString(int64Object)
+ ].equals(int64Object),
);
- assert.ok(
- EXPECTED_MIN_JS_SAFE_MINUS_ONE_INT64.equals(
- Int64Test.MIN_JS_SAFE_MINUS_ONE_INT64
- )
- );
- assert.ok(EXPECTED_MAX_SIGNED_INT64.equals(Int64Test.MAX_SIGNED_INT64));
- assert.ok(EXPECTED_MIN_SIGNED_INT64.equals(Int64Test.MIN_SIGNED_INT64));
- assert.equal(
- EXPECTED_SMALL_INT64_AS_NUMBER,
- Int64Test.SMALL_INT64.toNumber()
- );
- assert.equal(
- Number.MAX_SAFE_INTEGER,
- Int64Test.MAX_JS_SAFE_INT64.toNumber()
- );
- assert.equal(
- Number.MIN_SAFE_INTEGER,
- Int64Test.MIN_JS_SAFE_INT64.toNumber()
- );
+ }
- for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i) {
- assert.ok(EXPECTED_INT64_LIST[i].equals(Int64Test.INT64_LIST[i]));
- }
-
- for (let i = 0; i < EXPECTED_INT64_LIST.length; ++i){
- let int64Object = EXPECTED_INT64_LIST[i];
- assert.ok(Int64Test.INT64_2_INT64_MAP[JSONInt64.toDecimalString(int64Object)].equals(int64Object));
- }
-
- console.log('Int64 test -- ends');
- });
-
+ console.log("Int64 test -- ends");
+});
diff --git a/lib/ts/test/test.ts b/lib/ts/test/test.ts
index 31fdcbf..614461d 100644
--- a/lib/ts/test/test.ts
+++ b/lib/ts/test/test.ts
@@ -7,336 +7,365 @@
const transport: Thrift.Transport = new Thrift.Transport("/service");
const protocol: Thrift.Protocol = new Thrift.Protocol(transport);
-const client: ThriftTest.ThriftTestClient = new ThriftTest.ThriftTestClient(protocol);
+const client: ThriftTest.ThriftTestClient = new ThriftTest.ThriftTestClient(
+ protocol,
+);
-const int64_2_pow_60: typeof Int64 = new Int64('1000000000000000');
-const int64_minus_2_pow_60: typeof Int64 = new Int64('f000000000000000');
+const int64_2_pow_60: typeof Int64 = new Int64("1000000000000000");
+const int64_minus_2_pow_60: typeof Int64 = new Int64("f000000000000000");
// Work around for old API used by QUnitAdapter of jsTestDriver
-if (typeof QUnit.log == 'function') {
- // When using real QUnit (fron PhantomJS) log failures to console
- QUnit.log(function(details) {
- if (!details.result) {
- console.log('======== FAIL ========');
- console.log('TestName: ' + details.name);
- if (details.message) console.log(details.message);
- console.log('Expected: ' + JSONInt64.stringify(details.expected));
- console.log('Actual : ' + JSONInt64.stringify(details.actual));
- console.log('======================');
- }
- });
+if (typeof QUnit.log == "function") {
+ // When using real QUnit (fron PhantomJS) log failures to console
+ QUnit.log(function (details) {
+ if (!details.result) {
+ console.log("======== FAIL ========");
+ console.log("TestName: " + details.name);
+ if (details.message) console.log(details.message);
+ console.log("Expected: " + JSONInt64.stringify(details.expected));
+ console.log("Actual : " + JSONInt64.stringify(details.actual));
+ console.log("======================");
+ }
+ });
}
// all Languages in UTF-8
-const stringTest: string = "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語";
-
+const stringTest: string =
+ "Afrikaans, Alemannisch, Aragonés, العربية, مصرى, Asturianu, Aymar aru, Azərbaycan, Башҡорт, Boarisch, Žemaitėška, Беларуская, Беларуская (тарашкевіца), Български, Bamanankan, বাংলা, Brezhoneg, Bosanski, Català, Mìng-dĕ̤ng-ngṳ̄, Нохчийн, Cebuano, ᏣᎳᎩ, Česky, Словѣ́ньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ, Чӑвашла, Cymraeg, Dansk, Zazaki, ދިވެހިބަސް, Ελληνικά, Emiliàn e rumagnòl, English, Esperanto, Español, Eesti, Euskara, فارسی, Suomi, Võro, Føroyskt, Français, Arpetan, Furlan, Frysk, Gaeilge, 贛語, Gàidhlig, Galego, Avañe'ẽ, ગુજરાતી, Gaelg, עברית, हिन्दी, Fiji Hindi, Hrvatski, Kreyòl ayisyen, Magyar, Հայերեն, Interlingua, Bahasa Indonesia, Ilokano, Ido, Íslenska, Italiano, 日本語, Lojban, Basa Jawa, ქართული, Kongo, Kalaallisut, ಕನ್ನಡ, 한국어, Къарачай-Малкъар, Ripoarisch, Kurdî, Коми, Kernewek, Кыргызча, Latina, Ladino, Lëtzebuergesch, Limburgs, Lingála, ລາວ, Lietuvių, Latviešu, Basa Banyumasan, Malagasy, Македонски, മലയാളം, मराठी, Bahasa Melayu, مازِرونی, Nnapulitano, Nedersaksisch, नेपाल भाषा, Nederlands, Norsk (nynorsk), Norsk (bokmål), Nouormand, Diné bizaad, Occitan, Иронау, Papiamentu, Deitsch, Norfuk / Pitkern, Polski, پنجابی, پښتو, Português, Runa Simi, Rumantsch, Romani, Română, Русский, Саха тыла, Sardu, Sicilianu, Scots, Sámegiella, Simple English, Slovenčina, Slovenščina, Српски / Srpski, Seeltersk, Svenska, Kiswahili, தமிழ், తెలుగు, Тоҷикӣ, ไทย, Türkmençe, Tagalog, Türkçe, Татарча/Tatarça, Українська, اردو, Tiếng Việt, Volapük, Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, Bân-lâm-gú, 粵語";
function checkRecursively(assert, map1: Object, map2: Object): void {
- if (typeof map1 !== 'function' && typeof map2 !== 'function') {
- if (!map1 || typeof map1 !== 'object') {
- assert.equal(map1, map2);
- } else {
- for (let key in map1) {
- checkRecursively(assert, map1[key], map2[key]);
- }
- }
+ if (typeof map1 !== "function" && typeof map2 !== "function") {
+ if (!map1 || typeof map1 !== "object") {
+ assert.equal(map1, map2);
+ } else {
+ for (let key in map1) {
+ checkRecursively(assert, map1[key], map2[key]);
+ }
}
+ }
}
+QUnit.module("Base Types");
-QUnit.module('Base Types');
+QUnit.test("Void", function (assert) {
+ assert.equal(client.testVoid(), undefined);
+});
+QUnit.test("Binary (String)", function (assert) {
+ let binary: string = "";
+ for (let v = 255; v >= 0; --v) {
+ binary += String.fromCharCode(v);
+ }
+ assert.equal(client.testBinary(binary), binary);
+});
+QUnit.test("Binary (Uint8Array)", function (assert) {
+ let binary: string = "";
+ for (let v = 255; v >= 0; --v) {
+ binary += String.fromCharCode(v);
+ }
+ const arr: Uint8Array = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; ++i) {
+ arr[i] = binary[i].charCodeAt(0);
+ }
+ const hexEncodedString = Array.from(arr, function (byte) {
+ return String.fromCharCode(byte);
+ }).join("");
+ assert.equal(client.testBinary(hexEncodedString), binary);
+});
+QUnit.test("String", function (assert) {
+ assert.equal(client.testString(""), "");
+ assert.equal(client.testString(stringTest), stringTest);
- QUnit.test('Void', function(assert) {
- assert.equal(client.testVoid(), undefined);
- });
- QUnit.test('Binary (String)', function(assert) {
- let binary: string = '';
- for (let v = 255; v >= 0; --v) {
- binary += String.fromCharCode(v);
- }
- assert.equal(client.testBinary(binary), binary);
- });
- QUnit.test('Binary (Uint8Array)', function(assert) {
- let binary: string = '';
- for (let v = 255; v >= 0; --v) {
- binary += String.fromCharCode(v);
- }
- const arr: Uint8Array = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; ++i) {
- arr[i] = binary[i].charCodeAt(0);
- }
- const hexEncodedString = Array.from(arr, function(byte) {
- return String.fromCharCode(byte);
- }).join('')
- assert.equal(client.testBinary(hexEncodedString), binary);
- });
- QUnit.test('String', function(assert) {
- assert.equal(client.testString(''), '');
- assert.equal(client.testString(stringTest), stringTest);
+ const specialCharacters: string =
+ 'quote: \" backslash:' +
+ " forwardslash-escaped: \/ " +
+ " backspace: \b formfeed: \f newline: \n return: \r tab: " +
+ ' now-all-of-them-together: "\\\/\b\n\r\t' +
+ " now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><";
+ assert.equal(client.testString(specialCharacters), specialCharacters);
+});
+QUnit.test("Double", function (assert) {
+ assert.equal(client.testDouble(0), 0);
+ assert.equal(client.testDouble(-1), -1);
+ assert.equal(client.testDouble(3.14), 3.14);
+ assert.equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60));
+});
+QUnit.test("Byte", function (assert) {
+ assert.equal(client.testByte(0), 0);
+ assert.equal(client.testByte(0x01), 0x01);
+});
+QUnit.test("I32", function (assert) {
+ assert.equal(client.testI32(0), 0);
+ assert.equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30));
+ assert.equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30));
+});
+QUnit.test("I64", function (assert) {
+ assert.equal(client.testI64(new Int64(0)), 0);
- const specialCharacters: string = 'quote: \" backslash:' +
- ' forwardslash-escaped: \/ ' +
- ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
- ' now-all-of-them-together: "\\\/\b\n\r\t' +
- ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><';
- assert.equal(client.testString(specialCharacters), specialCharacters);
- });
- QUnit.test('Double', function(assert) {
- assert.equal(client.testDouble(0), 0);
- assert.equal(client.testDouble(-1), -1);
- assert.equal(client.testDouble(3.14), 3.14);
- assert.equal(client.testDouble(Math.pow(2, 60)), Math.pow(2, 60));
- });
- QUnit.test('Byte', function(assert) {
- assert.equal(client.testByte(0), 0);
- assert.equal(client.testByte(0x01), 0x01);
- });
- QUnit.test('I32', function(assert) {
- assert.equal(client.testI32(0), 0);
- assert.equal(client.testI32(Math.pow(2, 30)), Math.pow(2, 30));
- assert.equal(client.testI32(-Math.pow(2, 30)), -Math.pow(2, 30));
- });
- QUnit.test('I64', function(assert) {
- assert.equal(client.testI64(new Int64(0)), 0);
+ let int64_2_pow_60_result: typeof Int64 = client.testI64(int64_2_pow_60);
+ assert.ok(int64_2_pow_60.equals(int64_2_pow_60_result));
- let int64_2_pow_60_result: typeof Int64 = client.testI64(int64_2_pow_60);
- assert.ok(int64_2_pow_60.equals(int64_2_pow_60_result));
+ let int64_minus_2_pow_60_result: typeof Int64 =
+ client.testI64(int64_minus_2_pow_60);
+ assert.ok(int64_minus_2_pow_60.equals(int64_minus_2_pow_60_result));
+});
- let int64_minus_2_pow_60_result: typeof Int64 = client.testI64(int64_minus_2_pow_60);
- assert.ok(int64_minus_2_pow_60.equals(int64_minus_2_pow_60_result));
- });
+QUnit.module("Structured Types");
+QUnit.test("Struct", function (assert) {
+ const structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
+ structTestInput.string_thing = "worked";
+ structTestInput.byte_thing = 0x01;
+ structTestInput.i32_thing = Math.pow(2, 30);
+ structTestInput.i64_thing = int64_2_pow_60;
-QUnit.module('Structured Types');
+ const structTestOutput: ThriftTest.Xtruct =
+ client.testStruct(structTestInput);
- QUnit.test('Struct', function(assert) {
- const structTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
- structTestInput.string_thing = 'worked';
- structTestInput.byte_thing = 0x01;
- structTestInput.i32_thing = Math.pow(2, 30);
- structTestInput.i64_thing = int64_2_pow_60;
+ assert.equal(structTestOutput.string_thing, structTestInput.string_thing);
+ assert.equal(structTestOutput.byte_thing, structTestInput.byte_thing);
+ assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing);
+ assert.ok(structTestOutput.i64_thing.equals(structTestInput.i64_thing));
+ assert.ok(structTestInput.i64_thing.equals(structTestOutput.i64_thing));
- const structTestOutput: ThriftTest.Xtruct = client.testStruct(structTestInput);
+ assert.equal(
+ JSONInt64.stringify(structTestOutput),
+ JSONInt64.stringify(structTestInput),
+ );
+});
- assert.equal(structTestOutput.string_thing, structTestInput.string_thing);
- assert.equal(structTestOutput.byte_thing, structTestInput.byte_thing);
- assert.equal(structTestOutput.i32_thing, structTestInput.i32_thing);
- assert.ok(structTestOutput.i64_thing.equals(structTestInput.i64_thing));
- assert.ok(structTestInput.i64_thing.equals(structTestOutput.i64_thing));
+QUnit.test("Nest", function (assert) {
+ const xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
+ xtrTestInput.string_thing = "worked";
+ xtrTestInput.byte_thing = 0x01;
+ xtrTestInput.i32_thing = Math.pow(2, 30);
+ xtrTestInput.i64_thing = int64_2_pow_60;
- assert.equal(JSONInt64.stringify(structTestOutput), JSONInt64.stringify(structTestInput));
- });
+ const nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2();
+ nestTestInput.byte_thing = 0x02;
+ nestTestInput.struct_thing = xtrTestInput;
+ nestTestInput.i32_thing = Math.pow(2, 15);
- QUnit.test('Nest', function(assert) {
- const xtrTestInput: ThriftTest.Xtruct = new ThriftTest.Xtruct();
- xtrTestInput.string_thing = 'worked';
- xtrTestInput.byte_thing = 0x01;
- xtrTestInput.i32_thing = Math.pow(2, 30);
- xtrTestInput.i64_thing = int64_2_pow_60;
+ const nestTestOutput: ThriftTest.Xtruct2 = client.testNest(nestTestInput);
- const nestTestInput: ThriftTest.Xtruct2 = new ThriftTest.Xtruct2();
- nestTestInput.byte_thing = 0x02;
- nestTestInput.struct_thing = xtrTestInput;
- nestTestInput.i32_thing = Math.pow(2, 15);
+ assert.equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
+ assert.equal(
+ nestTestOutput.struct_thing.string_thing,
+ nestTestInput.struct_thing.string_thing,
+ );
+ assert.equal(
+ nestTestOutput.struct_thing.byte_thing,
+ nestTestInput.struct_thing.byte_thing,
+ );
+ assert.equal(
+ nestTestOutput.struct_thing.i32_thing,
+ nestTestInput.struct_thing.i32_thing,
+ );
+ assert.ok(
+ nestTestOutput.struct_thing.i64_thing.equals(
+ nestTestInput.struct_thing.i64_thing,
+ ),
+ );
+ assert.equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
- const nestTestOutput: ThriftTest.Xtruct2 = client.testNest(nestTestInput);
+ assert.equal(
+ JSONInt64.stringify(nestTestOutput),
+ JSONInt64.stringify(nestTestInput),
+ );
+});
- assert.equal(nestTestOutput.byte_thing, nestTestInput.byte_thing);
- assert.equal(nestTestOutput.struct_thing.string_thing, nestTestInput.struct_thing.string_thing);
- assert.equal(nestTestOutput.struct_thing.byte_thing, nestTestInput.struct_thing.byte_thing);
- assert.equal(nestTestOutput.struct_thing.i32_thing, nestTestInput.struct_thing.i32_thing);
- assert.ok(nestTestOutput.struct_thing.i64_thing.equals(nestTestInput.struct_thing.i64_thing));
- assert.equal(nestTestOutput.i32_thing, nestTestInput.i32_thing);
+QUnit.test("Map", function (assert) {
+ const mapTestInput: { [k: number]: number } = { 7: 77, 8: 88, 9: 99 };
- assert.equal(JSONInt64.stringify(nestTestOutput), JSONInt64.stringify(nestTestInput));
- });
-
- QUnit.test('Map', function(assert) {
- const mapTestInput: {[k: number]: number;} = {7: 77, 8: 88, 9: 99};
-
- const mapTestOutput: {[k: number]: number;} = client.testMap(mapTestInput);
-
- for (let key in mapTestOutput) {
- assert.equal(mapTestOutput[key], mapTestInput[key]);
- }
- });
-
- QUnit.test('StringMap', function(assert) {
- const mapTestInput: {[k: string]: string;} = {
- 'a': '123', 'a b': 'with spaces ', 'same': 'same', '0': 'numeric key',
- 'longValue': stringTest, stringTest: 'long key'
- };
-
- const mapTestOutput: {[k: string]: string;} = client.testStringMap(mapTestInput);
-
- for (let key in mapTestOutput) {
- assert.equal(mapTestOutput[key], mapTestInput[key]);
- }
- });
-
- QUnit.test('Set', function(assert) {
- const setTestInput: number[] = [1, 2, 3];
- assert.ok(client.testSet(setTestInput), setTestInput);
- });
-
- QUnit.test('List', function(assert) {
- const listTestInput: number[] = [1, 2, 3];
- assert.ok(client.testList(listTestInput), listTestInput);
- });
-
- QUnit.test('Enum', function(assert) {
- assert.equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
- });
-
- QUnit.test('TypeDef', function(assert) {
- assert.equal(client.testTypedef(new Int64(69)), 69);
- });
+ const mapTestOutput: { [k: number]: number } = client.testMap(mapTestInput);
+ for (let key in mapTestOutput) {
+ assert.equal(mapTestOutput[key], mapTestInput[key]);
+ }
+});
-QUnit.module('deeper!');
+QUnit.test("StringMap", function (assert) {
+ const mapTestInput: { [k: string]: string } = {
+ a: "123",
+ "a b": "with spaces ",
+ same: "same",
+ "0": "numeric key",
+ longValue: stringTest,
+ stringTest: "long key",
+ };
- QUnit.test('MapMap', function(assert) {
- const mapMapTestExpectedResult: {[K: number]: {[k: number]: number}} = {
- '4': {'1': 1, '2': 2, '3': 3, '4': 4},
- '-4': {'-4': -4, '-3': -3, '-2': -2, '-1': -1}
- };
-
- const mapMapTestOutput = client.testMapMap(1);
-
-
- for (let key in mapMapTestOutput) {
- for (let key2 in mapMapTestOutput[key]) {
- assert.equal(mapMapTestOutput[key][key2], mapMapTestExpectedResult[key][key2]);
- }
- }
-
- checkRecursively(assert, mapMapTestOutput, mapMapTestExpectedResult);
- });
+ const mapTestOutput: { [k: string]: string } =
+ client.testStringMap(mapTestInput);
+ for (let key in mapTestOutput) {
+ assert.equal(mapTestOutput[key], mapTestInput[key]);
+ }
+});
-QUnit.module('Exception');
+QUnit.test("Set", function (assert) {
+ const setTestInput: number[] = [1, 2, 3];
+ assert.ok(client.testSet(setTestInput), setTestInput);
+});
- QUnit.test('Xception', function(assert) {
- assert.expect(2);
- const done = assert.async();
- try {
- client.testException('Xception');
- assert.ok(false);
- }catch (e) {
- assert.equal(e.errorCode, 1001);
- assert.equal(e.message, 'Xception');
- done();
- }
- });
-
- QUnit.test('no Exception', function(assert) {
- assert.expect(1);
- try {
- client.testException('no Exception');
- assert.ok(true);
- }catch (e) {
- assert.ok(false);
- }
- });
-
- QUnit.test('TException', function(assert) {
- //ThriftTest does not list TException as a legal exception so it will
- // generate an exception on the server that does not propagate back to
- // the client. This test has been modified to equate to "no exception"
- assert.expect(1);
- try {
- client.testException('TException');
- } catch (e) {
- //assert.ok(false);
- }
- assert.ok(true);
- });
+QUnit.test("List", function (assert) {
+ const listTestInput: number[] = [1, 2, 3];
+ assert.ok(client.testList(listTestInput), listTestInput);
+});
+QUnit.test("Enum", function (assert) {
+ assert.equal(client.testEnum(ThriftTest.Numberz.ONE), ThriftTest.Numberz.ONE);
+});
-QUnit.module('Insanity');
+QUnit.test("TypeDef", function (assert) {
+ assert.equal(client.testTypedef(new Int64(69)), 69);
+});
- const crazy: ThriftTest.Insanity = {
- 'userMap': { '5': new Int64(5), '8': new Int64(8) },
- 'xtructs': [{
- 'string_thing': 'Goodbye4',
- 'byte_thing': 4,
- 'i32_thing': 4,
- 'i64_thing': new Int64(4)
- },
- {
- 'string_thing': 'Hello2',
- 'byte_thing': 2,
- 'i32_thing': 2,
- 'i64_thing': new Int64(2)
- }]
- };
- QUnit.test('testInsanity', function(assert) {
- const insanity: {[k: number]: (ThriftTest.Insanity | {[k:number]: ThriftTest.Insanity})} = {
- '1': {
- '2': crazy,
- '3': crazy
- },
- '2': { '6': new ThriftTest.Insanity() }
- };
- const res = client.testInsanity(new ThriftTest.Insanity(crazy));
- assert.ok(res, JSONInt64.stringify(res));
- assert.ok(insanity, JSONInt64.stringify(insanity));
-
- checkRecursively(assert, res, insanity);
- });
+QUnit.module("deeper!");
+QUnit.test("MapMap", function (assert) {
+ const mapMapTestExpectedResult: { [K: number]: { [k: number]: number } } = {
+ "4": { "1": 1, "2": 2, "3": 3, "4": 4 },
+ "-4": { "-4": -4, "-3": -3, "-2": -2, "-1": -1 },
+ };
+
+ const mapMapTestOutput = client.testMapMap(1);
+
+ for (let key in mapMapTestOutput) {
+ for (let key2 in mapMapTestOutput[key]) {
+ assert.equal(
+ mapMapTestOutput[key][key2],
+ mapMapTestExpectedResult[key][key2],
+ );
+ }
+ }
+
+ checkRecursively(assert, mapMapTestOutput, mapMapTestExpectedResult);
+});
+
+QUnit.module("Exception");
+
+QUnit.test("Xception", function (assert) {
+ assert.expect(2);
+ const done = assert.async();
+ try {
+ client.testException("Xception");
+ assert.ok(false);
+ } catch (e) {
+ assert.equal(e.errorCode, 1001);
+ assert.equal(e.message, "Xception");
+ done();
+ }
+});
+
+QUnit.test("no Exception", function (assert) {
+ assert.expect(1);
+ try {
+ client.testException("no Exception");
+ assert.ok(true);
+ } catch (e) {
+ assert.ok(false);
+ }
+});
+
+QUnit.test("TException", function (assert) {
+ //ThriftTest does not list TException as a legal exception so it will
+ // generate an exception on the server that does not propagate back to
+ // the client. This test has been modified to equate to "no exception"
+ assert.expect(1);
+ try {
+ client.testException("TException");
+ } catch (e) {
+ //assert.ok(false);
+ }
+ assert.ok(true);
+});
+
+QUnit.module("Insanity");
+
+const crazy: ThriftTest.Insanity = {
+ userMap: { "5": new Int64(5), "8": new Int64(8) },
+ xtructs: [
+ {
+ string_thing: "Goodbye4",
+ byte_thing: 4,
+ i32_thing: 4,
+ i64_thing: new Int64(4),
+ },
+ {
+ string_thing: "Hello2",
+ byte_thing: 2,
+ i32_thing: 2,
+ i64_thing: new Int64(2),
+ },
+ ],
+};
+QUnit.test("testInsanity", function (assert) {
+ const insanity: {
+ [k: number]: ThriftTest.Insanity | { [k: number]: ThriftTest.Insanity };
+ } = {
+ "1": {
+ "2": crazy,
+ "3": crazy,
+ },
+ "2": { "6": new ThriftTest.Insanity() },
+ };
+ const res = client.testInsanity(new ThriftTest.Insanity(crazy));
+ assert.ok(res, JSONInt64.stringify(res));
+ assert.ok(insanity, JSONInt64.stringify(insanity));
+
+ checkRecursively(assert, res, insanity);
+});
//////////////////////////////////
//Run same tests asynchronously
-QUnit.module('Async');
+QUnit.module("Async");
- QUnit.test('Double', function(assert) {
- assert.expect(1);
+QUnit.test("Double", function (assert) {
+ assert.expect(1);
- const done = assert.async();
- client.testDouble(3.14159265, function(result) {
- assert.equal(result, 3.14159265);
- done();
- });
- });
+ const done = assert.async();
+ client.testDouble(3.14159265, function (result) {
+ assert.equal(result, 3.14159265);
+ done();
+ });
+});
- QUnit.test('Byte', function(assert) {
- assert.expect(1);
+QUnit.test("Byte", function (assert) {
+ assert.expect(1);
- const done = assert.async();
- client.testByte(0x01, function(result) {
- assert.equal(result, 0x01);
- done();
- });
- });
+ const done = assert.async();
+ client.testByte(0x01, function (result) {
+ assert.equal(result, 0x01);
+ done();
+ });
+});
- QUnit.test('I32', function(assert) {
- assert.expect(2);
+QUnit.test("I32", function (assert) {
+ assert.expect(2);
- const done = assert.async(2);
- client.testI32(Math.pow(2, 30), function(result) {
- assert.equal(result, Math.pow(2, 30));
- done();
- });
+ const done = assert.async(2);
+ client.testI32(Math.pow(2, 30), function (result) {
+ assert.equal(result, Math.pow(2, 30));
+ done();
+ });
- client.testI32(Math.pow(-2, 31), function(result) {
- assert.equal(result, Math.pow(-2, 31));
- done();
- });
- });
+ client.testI32(Math.pow(-2, 31), function (result) {
+ assert.equal(result, Math.pow(-2, 31));
+ done();
+ });
+});
- QUnit.test('I64', function(assert) {
- assert.expect(2);
+QUnit.test("I64", function (assert) {
+ assert.expect(2);
- const done = assert.async(2);
- client.testI64(int64_2_pow_60, function(result) {
- assert.ok(int64_2_pow_60.equals(result));
- done();
- });
+ const done = assert.async(2);
+ client.testI64(int64_2_pow_60, function (result) {
+ assert.ok(int64_2_pow_60.equals(result));
+ done();
+ });
- client.testI64(int64_minus_2_pow_60, function(result) {
- assert.ok(int64_minus_2_pow_60.equals(result));
- done();
- });
- });
+ client.testI64(int64_minus_2_pow_60, function (result) {
+ assert.ok(int64_minus_2_pow_60.equals(result));
+ done();
+ });
+});
diff --git a/lib/ts/test/test_handler.js b/lib/ts/test/test_handler.js
index 8ba296b..825c567 100644
--- a/lib/ts/test/test_handler.js
+++ b/lib/ts/test/test_handler.js
@@ -20,87 +20,87 @@
//This is the server side Node test handler for the standard
// Apache Thrift test service.
-const es6Mode = process.argv.includes('--es6');
-const genFolder = es6Mode ? 'gen-nodejs-es6' : 'gen-nodejs';
+const es6Mode = process.argv.includes("--es6");
+const genFolder = es6Mode ? "gen-nodejs-es6" : "gen-nodejs";
const ttypes = require(`./${genFolder}/ThriftTest_types`);
-const TException = require('../../nodejs/lib/thrift').TException;
-const Int64 = require('node-int64');
+const TException = require("../../nodejs/lib/thrift").TException;
+const Int64 = require("node-int64");
exports.ThriftTestHandler = {
- testVoid: function(result) {
- console.log('testVoid()');
+ testVoid: function (result) {
+ console.log("testVoid()");
result(null);
},
- testString: function(thing, result) {
- console.log('testString(\'' + thing + '\')');
+ testString: function (thing, result) {
+ console.log("testString('" + thing + "')");
result(null, thing);
},
- testByte: function(thing, result) {
- console.log('testByte(' + thing + ')');
+ testByte: function (thing, result) {
+ console.log("testByte(" + thing + ")");
result(null, thing);
},
- testI32: function(thing, result) {
- console.log('testI32(' + thing + ')');
+ testI32: function (thing, result) {
+ console.log("testI32(" + thing + ")");
result(null, thing);
},
- testI64: function(thing, result) {
- console.log('testI64(' + thing + ')');
+ testI64: function (thing, result) {
+ console.log("testI64(" + thing + ")");
result(null, thing);
},
- testDouble: function(thing, result) {
- console.log('testDouble(' + thing + ')');
+ testDouble: function (thing, result) {
+ console.log("testDouble(" + thing + ")");
result(null, thing);
},
- testBinary: function(thing, result) {
- console.log('testBinary(\'' + thing + '\')');
+ testBinary: function (thing, result) {
+ console.log("testBinary('" + thing + "')");
result(null, thing);
},
- testStruct: function(thing, result) {
- console.log('testStruct(');
+ testStruct: function (thing, result) {
+ console.log("testStruct(");
console.log(thing);
- console.log(')');
+ console.log(")");
result(null, thing);
},
- testNest: function(nest, result) {
- console.log('testNest(');
+ testNest: function (nest, result) {
+ console.log("testNest(");
console.log(nest);
- console.log(')');
+ console.log(")");
result(null, nest);
},
- testMap: function(thing, result) {
- console.log('testMap(');
+ testMap: function (thing, result) {
+ console.log("testMap(");
console.log(thing);
- console.log(')');
+ console.log(")");
result(null, thing);
},
- testStringMap: function(thing, result) {
- console.log('testStringMap(');
+ testStringMap: function (thing, result) {
+ console.log("testStringMap(");
console.log(thing);
- console.log(')');
+ console.log(")");
result(null, thing);
},
- testSet: function(thing, result) {
- console.log('testSet(');
+ testSet: function (thing, result) {
+ console.log("testSet(");
console.log(thing);
- console.log(')');
+ console.log(")");
result(null, thing);
},
- testList: function(thing, result) {
- console.log('testList(');
+ testList: function (thing, result) {
+ console.log("testList(");
console.log(thing);
- console.log(')');
+ console.log(")");
result(null, thing);
},
- testEnum: function(thing, result) {
- console.log('testEnum(' + thing + ')');
+ testEnum: function (thing, result) {
+ console.log("testEnum(" + thing + ")");
result(null, thing);
},
- testTypedef: function(thing, result) {
- console.log('testTypedef(' + thing + ')');
+ testTypedef: function (thing, result) {
+ console.log("testTypedef(" + thing + ")");
result(null, thing);
},
- testMapMap: function(hello, result) {
- console.log('testMapMap(' + hello + ')');
+ testMapMap: function (hello, result) {
+ console.log("testMapMap(" + hello + ")");
const mapmap = [];
const pos = [];
@@ -114,19 +114,19 @@
result(null, mapmap);
},
- testInsanity: function(argument, result) {
- console.log('testInsanity(');
+ testInsanity: function (argument, result) {
+ console.log("testInsanity(");
console.log(argument);
- console.log(')');
+ console.log(")");
const hello = new ttypes.Xtruct();
- hello.string_thing = 'Hello2';
+ hello.string_thing = "Hello2";
hello.byte_thing = 2;
hello.i32_thing = 2;
hello.i64_thing = new Int64(2);
const goodbye = new ttypes.Xtruct();
- goodbye.string_thing = 'Goodbye4';
+ goodbye.string_thing = "Goodbye4";
goodbye.byte_thing = 4;
goodbye.i32_thing = 4;
goodbye.i64_thing = new Int64(4);
@@ -150,45 +150,45 @@
insane[1] = first_map;
insane[2] = second_map;
- console.log('insane result:');
+ console.log("insane result:");
console.log(insane);
result(null, insane);
},
- testMulti: function(arg0, arg1, arg2, arg3, arg4, arg5, result) {
- console.log('testMulti()');
+ testMulti: function (arg0, arg1, arg2, arg3, arg4, arg5, result) {
+ console.log("testMulti()");
const hello = new ttypes.Xtruct();
- hello.string_thing = 'Hello2';
+ hello.string_thing = "Hello2";
hello.byte_thing = arg0;
hello.i32_thing = arg1;
hello.i64_thing = arg2;
result(null, hello);
},
- testException: function(arg, result) {
- console.log('testException(' + arg + ')');
- if (arg === 'Xception') {
+ testException: function (arg, result) {
+ console.log("testException(" + arg + ")");
+ if (arg === "Xception") {
const x = new ttypes.Xception();
x.errorCode = 1001;
x.message = arg;
result(x);
- } else if (arg === 'TException') {
+ } else if (arg === "TException") {
result(new TException(arg));
} else {
result(null);
}
},
- testMultiException: function(arg0, arg1, result) {
- console.log('testMultiException(' + arg0 + ', ' + arg1 + ')');
- if (arg0 === ('Xception')) {
+ testMultiException: function (arg0, arg1, result) {
+ console.log("testMultiException(" + arg0 + ", " + arg1 + ")");
+ if (arg0 === "Xception") {
const x = new ttypes.Xception();
x.errorCode = 1001;
- x.message = 'This is an Xception';
+ x.message = "This is an Xception";
result(x);
- } else if (arg0 === ('Xception2')) {
+ } else if (arg0 === "Xception2") {
const x2 = new ttypes.Xception2();
x2.errorCode = 2002;
x2.struct_thing = new ttypes.Xtruct();
- x2.struct_thing.string_thing = 'This is an Xception2';
+ x2.struct_thing.string_thing = "This is an Xception2";
result(x2);
}
@@ -196,7 +196,9 @@
res.string_thing = arg1;
result(null, res);
},
- testOneway: function(sleepFor, result) {
- console.log('testOneway(' + sleepFor + ') => JavaScript (like Rust) never sleeps!');
- }
-}; //ThriftTestSvcHandler
+ testOneway: function (sleepFor, result) {
+ console.log(
+ "testOneway(" + sleepFor + ") => JavaScript (like Rust) never sleeps!",
+ );
+ },
+}; //ThriftTestSvcHandler
diff --git a/lib/ts/thrift.d.ts b/lib/ts/thrift.d.ts
index 0ba46c9..8e9d565 100644
--- a/lib/ts/thrift.d.ts
+++ b/lib/ts/thrift.d.ts
@@ -29,7 +29,7 @@
* @property {number} VOID - No value (only legal for return types).
* @property {number} BOOL - True/False integer.
* @property {number} BYTE - Signed 8 bit integer.
- * @property {number} I08 - Signed 8 bit integer.
+ * @property {number} I08 - Signed 8 bit integer.
* @property {number} DOUBLE - 64 bit IEEE 854 floating point.
* @property {number} I16 - Signed 16 bit integer.
* @property {number} I32 - Signed 32 bit integer.
@@ -44,23 +44,23 @@
* @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters.
*/
interface Type {
- 'STOP': number;
- 'VOID': number;
- 'BOOL': number;
- 'BYTE': number;
- 'I08': number;
- 'DOUBLE': number;
- 'I16': number;
- 'I32': number;
- 'I64': number;
- 'STRING': number;
- 'UTF7': number;
- 'STRUCT': number;
- 'MAP': number;
- 'SET': number;
- 'LIST': number;
- 'UTF8': number;
- 'UTF16': number;
+ STOP: number;
+ VOID: number;
+ BOOL: number;
+ BYTE: number;
+ I08: number;
+ DOUBLE: number;
+ I16: number;
+ I32: number;
+ I64: number;
+ STRING: number;
+ UTF7: number;
+ STRUCT: number;
+ MAP: number;
+ SET: number;
+ LIST: number;
+ UTF8: number;
+ UTF16: number;
}
var Type: Type;
@@ -72,10 +72,10 @@
* @property {number} ONEWAY - Oneway RPC call from client to server with no response.
*/
interface MessageType {
- 'CALL': number;
- 'REPLY': number;
- 'EXCEPTION': number;
- 'ONEWAY': number;
+ CALL: number;
+ REPLY: number;
+ EXCEPTION: number;
+ ONEWAY: number;
}
var MessageType: MessageType;
@@ -92,7 +92,11 @@
* @param {function} superConstructor - Contstructor function to set as base.
* @param {string} [name] - Type name to set as name property in derived prototype.
*/
- function inherits(constructor: Function, superConstructor: Function, name?: string): void;
+ function inherits(
+ constructor: Function,
+ superConstructor: Function,
+ name?: string,
+ ): void;
/**
* TException is the base class for all Thrift exceptions types.
@@ -129,17 +133,17 @@
* @property {number} UNSUPPORTED_CLIENT_TYPE - Unused.
*/
interface TApplicationExceptionType {
- 'UNKNOWN': number;
- 'UNKNOWN_METHOD': number;
- 'INVALID_MESSAGE_TYPE': number;
- 'WRONG_METHOD_NAME': number;
- 'BAD_SEQUENCE_ID': number;
- 'MISSING_RESULT': number;
- 'INTERNAL_ERROR': number;
- 'PROTOCOL_ERROR': number;
- 'INVALID_TRANSFORM': number;
- 'INVALID_PROTOCOL': number;
- 'UNSUPPORTED_CLIENT_TYPE': number;
+ UNKNOWN: number;
+ UNKNOWN_METHOD: number;
+ INVALID_MESSAGE_TYPE: number;
+ WRONG_METHOD_NAME: number;
+ BAD_SEQUENCE_ID: number;
+ MISSING_RESULT: number;
+ INTERNAL_ERROR: number;
+ PROTOCOL_ERROR: number;
+ INVALID_TRANSFORM: number;
+ INVALID_PROTOCOL: number;
+ UNSUPPORTED_CLIENT_TYPE: number;
}
var TApplicationExceptionType: TApplicationExceptionType;
@@ -179,7 +183,7 @@
/**
* The Apache Thrift Transport layer performs byte level I/O between RPC
* clients and servers. The JavaScript Transport object type uses Http[s]/XHR and is
- * the sole browser based Thrift transport. Target servers must implement the http[s]
+ * the sole browser based Thrift transport. Target servers must implement the http[s]
* transport (see: node.js example server).
*/
class TXHRTransport {
@@ -208,7 +212,7 @@
/**
* Sends the current XRH request if the transport was created with a URL and
* the async parameter if false. If the transport was not created with a URL
- * or the async parameter is True or the URL is an empty string, the current
+ * or the async parameter is True or the URL is an empty string, the current
* send buffer is returned.
* @param {object} async - If true the current send buffer is returned.
* @param {function} callback - Optional async completion callback.
@@ -224,7 +228,12 @@
* @param {function} recv_method - The Thrift Service Client receive method for the call.
* @returns {object} A new jQuery XHR object.
*/
- jqRequest(client: Object, postData: any, args: Function, recv_method: Function): Object;
+ jqRequest(
+ client: Object,
+ postData: any,
+ args: Function,
+ recv_method: Function,
+ ): Object;
/**
* Sets the buffer to use when receiving server responses.
@@ -281,22 +290,22 @@
/**
* Old alias of the TXHRTransport for backwards compatibility.
*/
- class Transport extends TXHRTransport { }
+ class Transport extends TXHRTransport {}
/**
- * The Apache Thrift Transport layer performs byte level I/O
- * between RPC clients and servers. The JavaScript TWebSocketTransport object
+ * The Apache Thrift Transport layer performs byte level I/O
+ * between RPC clients and servers. The JavaScript TWebSocketTransport object
* uses the WebSocket protocol. Target servers must implement WebSocket.
*/
class TWebSocketTransport {
- url: string; //Where to connect
- socket: any; //The web socket
+ url: string; //Where to connect
+ socket: any; //The web socket
callbacks: Function[]; //Pending callbacks
- send_pending: any[]; //Buffers/Callback pairs waiting to be sent
- send_buf: string; //Outbound data, immutable until sent
- recv_buf: string; //Inbound data
- rb_wpos: number; //Network write position in receive buffer
- rb_rpos: number; //Client read position in receive buffer
+ send_pending: any[]; //Buffers/Callback pairs waiting to be sent
+ send_buf: string; //Outbound data, immutable until sent
+ recv_buf: string; //Inbound data
+ rb_wpos: number; //Network write position in receive buffer
+ rb_rpos: number; //Client read position in receive buffer
/**
* Constructor Function for the WebSocket transport.
@@ -307,12 +316,12 @@
__reset(url: string): void;
/**
- * Sends the current WS request and registers callback. The async
- * parameter is ignored (WS flush is always async) and the callback
+ * Sends the current WS request and registers callback. The async
+ * parameter is ignored (WS flush is always async) and the callback
* function parameter is required.
* @param {object} async - Ignored.
* @param {function} callback - The client completion callback.
- * @returns {undefined|string} Nothing (undefined)
+ * @returns {undefined|string} Nothing (undefined)
*/
flush(async: any, callback: Function): string;
@@ -332,7 +341,7 @@
/**
* Returns true if the transport is open
- * @returns {boolean}
+ * @returns {boolean}
*/
isOpen(): boolean;
@@ -374,8 +383,8 @@
}
/**
- * Apache Thrift Protocols perform serialization which enables cross
- * language RPC. The Protocol type is the JavaScript browser implementation
+ * Apache Thrift Protocols perform serialization which enables cross
+ * language RPC. The Protocol type is the JavaScript browser implementation
* of the Apache Thrift TJSONProtocol.
*/
class TJSONProtocol {
@@ -401,17 +410,17 @@
/**
* Thrift IDL type string to Id mapping.
* The mapping table looks as follows:
- * "tf" -> Thrift.Type.BOOL
- * "i8" -> Thrift.Type.BYTE
- * "i16" -> Thrift.Type.I16
- * "i32" -> Thrift.Type.I32
- * "i64" -> Thrift.Type.I64
+ * "tf" -> Thrift.Type.BOOL
+ * "i8" -> Thrift.Type.BYTE
+ * "i16" -> Thrift.Type.I16
+ * "i32" -> Thrift.Type.I32
+ * "i64" -> Thrift.Type.I64
* "dbl" -> Thrift.Type.DOUBLE
* "rec" -> Thrift.Type.STRUCT
* "str" -> Thrift.Type.STRING
- * "map" -> Thrift.Type.MAP
- * "lst" -> Thrift.Type.LIST
- * "set" -> Thrift.Type.SET
+ * "map" -> Thrift.Type.MAP
+ * "lst" -> Thrift.Type.LIST
+ * "set" -> Thrift.Type.SET
*/
RType: { [k: string]: number };
@@ -542,8 +551,8 @@
@property {Thrift.MessageType} mtype - The type of message call.
@property {number} rseqid - The sequence number of the message (0 in Thrift RPC).
*/
- /**
- * Deserializes the beginning of a message.
+ /**
+ * Deserializes the beginning of a message.
* @returns {AnonReadMessageBeginReturn}
*/
readMessageBegin(): { fname: string; mtype: number; rseqid: number };
@@ -551,8 +560,8 @@
/** Deserializes the end of a message. */
readMessageEnd(): void;
- /**
- * Deserializes the beginning of a struct.
+ /**
+ * Deserializes the beginning of a struct.
* @param {string} [name] - The name of the struct (ignored).
* @returns {object} - An object with an empty string fname property.
*/
@@ -568,8 +577,8 @@
@property {Thrift.Type} ftype - The data type of the field.
@property {number} fid - The unique identifier of the field.
*/
- /**
- * Deserializes the beginning of a field.
+ /**
+ * Deserializes the beginning of a field.
* @returns {AnonReadFieldBeginReturn}
*/
readFieldBegin(): { fname: string; ftype: number; fid: number };
@@ -584,8 +593,8 @@
@property {Thrift.Type} vtype - The data type of the value.
@property {number} size - The number of elements in the map.
*/
- /**
- * Deserializes the beginning of a map.
+ /**
+ * Deserializes the beginning of a map.
* @returns {AnonReadMapBeginReturn}
*/
readMapBegin(): { ktype: number; vtype: number; size: number };
@@ -599,8 +608,8 @@
@property {Thrift.Type} etype - The data type of the element.
@property {number} size - The number of elements in the collection.
*/
- /**
- * Deserializes the beginning of a list.
+ /**
+ * Deserializes the beginning of a list.
* @returns {AnonReadColBeginReturn}
*/
readListBegin(): { etype: number; size: number };
@@ -608,19 +617,22 @@
/** Deserializes the end of a list. */
readListEnd(): void;
- /**
- * Deserializes the beginning of a set.
+ /**
+ * Deserializes the beginning of a set.
* @param {Thrift.Type} elemType - The data type of the elements (ignored).
* @param {number} size - The number of elements in the list (ignored).
* @returns {AnonReadColBeginReturn}
*/
- readSetBegin(elemType?: number, size?: number): { etype: number; size: number };
+ readSetBegin(
+ elemType?: number,
+ size?: number,
+ ): { etype: number; size: number };
/** Deserializes the end of a set. */
readSetEnd(): void;
- /** Returns an object with a value property set to
- * False unless the next number in the protocol buffer
+ /** Returns an object with a value property set to
+ * False unless the next number in the protocol buffer
* is 1, in which case the value property is True. */
readBool(): Object;
@@ -652,7 +664,7 @@
next value found in the protocol buffer. */
readBinary(): Object;
- /**
+ /**
* Method to arbitrarily skip over data (not implemented).
*/
skip(type: number): void;
@@ -661,7 +673,7 @@
/**
* Old alias of the TXHRTransport for backwards compatibility.
*/
- class Protocol extends TJSONProtocol { }
+ class Protocol extends TJSONProtocol {}
class MultiplexProtocol extends TJSONProtocol {
serviceName: string;
@@ -673,7 +685,12 @@
* @param {any} [strictRead]
* @param {any} [strictWrite]
*/
- constructor(srvName: string, trans: Object, strictRead?: any, strictWrite?: any);
+ constructor(
+ srvName: string,
+ trans: Object,
+ strictRead?: any,
+ strictWrite?: any,
+ );
/**
* Override writeMessageBegin method of prototype