From 39ecdfed00db57574535ec57d071ce8bd5d31a19 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 24 Jul 2015 02:57:17 -0600 Subject: [PATCH] more testing (almost usable) --- client.js | 44 ++++++++++++++++++++++++++++++++++++++------ server.js | 17 +++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/client.js b/client.js index 015fd34..562ee1e 100644 --- a/client.js +++ b/client.js @@ -71,11 +71,13 @@ function create(opts) { // TODO maybe use HTTP POST instead? return getConnection(opts).then(function (ws) { if (ws.masterClient) { + console.log('[MASTER CLIENT] found'); return ws.masterClient; } var db = {}; var proto = sqlite3real.Database.prototype; + var messages = []; function rpc(fname, args) { var id; @@ -86,31 +88,52 @@ function create(opts) { cb = args.pop(); } - ws.send({ + console.log('fname, args'); + console.log(fname, args); + + ws.send(JSON.stringify({ type: 'rpc' , func: fname , args: args , filename: opts.filename , id: id - }); + })); if (!cb) { return; } function onMessage(data) { - if (!data || 'object' !== typeof data) { + var cmd; + + try { + cmd = JSON.parse(data.toString('utf8')); + } catch(e) { + console.error('[ERROR] in client, from sql server parse json'); + console.error(e); + console.error(data); + console.error(); + + //ws.send(JSON.stringify({ type: 'error', value: { message: e.message, code: "E_PARSE_JSON" } })); return; } - if (data.id !== id) { + if (cmd.id !== id) { return; } - cb.apply(data.this, data.args); + //console.log('onMessage data'); + //console.log(cmd); + + cb.apply(cmd.this, cmd.args); + + if ('on' !== fname) { + var index = messages.indexOf(onMessage); + messages.splice(index, 1); + } } - ws.on('message', onMessage); + messages.push(onMessage); } db.sanitize = require('./wrapper').sanitize; @@ -125,6 +148,15 @@ function create(opts) { }); + ws.on('message', function (data) { + messages.forEach(function (fn) { + try { + fn(data); + } catch(e) { + // ignore + } + }); + }); // serialize // parallel diff --git a/server.js b/server.js index fbe2000..20421c1 100644 --- a/server.js +++ b/server.js @@ -24,12 +24,18 @@ function createApp(server, options) { ws.__session_id = location.query.session_id || Math.random(); ws.on('message', function (buffer) { + console.log('[SERVER MESSAGE]', buffer); var cmd; try { cmd = JSON.parse(buffer.toString('utf8')); } catch(e) { + console.error('[ERROR] parse json'); + console.error(e); + console.error(buffer); + console.error(); ws.send(JSON.stringify({ type: 'error', value: { message: e.message, code: "E_PARSE_JSON" } })); + return; } switch(cmd.type) { @@ -37,6 +43,17 @@ function createApp(server, options) { break; case 'rpc': + cmd.args.push(function () { + var args = Array.prototype.slice.call(arguments); + + ws.send(JSON.stringify({ + this: this + , args: args + , id: cmd.id + })); + }); + + db[cmd.func].apply(db, cmd.args); break; default: