From a9460957da12f59b1c7048668161c71f9ae81a1f Mon Sep 17 00:00:00 2001 From: azivner Date: Tue, 28 Nov 2017 22:01:02 -0500 Subject: [PATCH] prototype of executing requests without network calls in electron --- app.js | 27 ++++++++++++++++++++++ public/javascripts/server.js | 43 +++++++++++++++++++++++++++++++----- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/app.js b/app.js index 40e9d5957..77165068a 100644 --- a/app.js +++ b/app.js @@ -9,6 +9,7 @@ const session = require('express-session'); const FileStore = require('session-file-store')(session); const os = require('os'); const sessionSecret = require('./services/session_secret'); +const utils = require('./services/utils'); require('./services/ping_job'); @@ -71,4 +72,30 @@ require('./services/sync'); // triggers backup timer require('./services/backup'); +if (utils.isElectron()) { + const ipcMain = require('electron').ipcMain; + + ipcMain.on('server-request', (event, arg) => { + const req = {}; + req.url = arg.url; + req.method = arg.method; + req.body = arg.data; + req.headers = {}; + + const res = {}; + res.setHeader = function() { + + }; + + res.send = function(obj) { + event.sender.send('server-response', { + requestId: arg.requestId, + body: obj + }); + }; + + return app._router.handle(req, res, () => {}); + }); +} + module.exports = app; \ No newline at end of file diff --git a/public/javascripts/server.js b/public/javascripts/server.js index 27d2cbae8..e8f53bf27 100644 --- a/public/javascripts/server.js +++ b/public/javascripts/server.js @@ -8,22 +8,54 @@ const server = (function() { } async function get(url) { - return await ajax('GET', url); + return await call('GET', url); } async function post(url, data) { - return await ajax('POST', url, data); + return await call('POST', url, data); } async function put(url, data) { - return await ajax('PUT', url, data); + return await call('PUT', url, data); } async function remove(url) { - return await ajax('DELETE', url); + return await call('DELETE', url); } - async function ajax(method, url, data) { + let i = 1; + const reqResolves = {}; + + async function call(method, url, data) { + if (isElectron()) { + const ipc = require('electron').ipcRenderer; + const requestId = i++; + + return new Promise((resolve, reject) => { + reqResolves[requestId] = resolve; + + ipc.send('server-request', { + requestId: requestId, + method: method, + url: "/" + baseApiUrl + url, + data: data + }); + }); + } + else { + return await ajax(url, method, data); + } + } + + if (isElectron()) { + const ipc = require('electron').ipcRenderer; + + ipc.on('server-response', (event, arg) => { + reqResolves[arg.requestId](arg.body); + }); + } + + async function ajax(url, method, data) { const options = { url: baseApiUrl + url, type: method @@ -39,6 +71,7 @@ const server = (function() { }); } + initAjax(); return {