prototype of executing requests without network calls in electron

This commit is contained in:
azivner 2017-11-28 22:01:02 -05:00
parent 54c0ff15b3
commit a9460957da
2 changed files with 65 additions and 5 deletions

27
app.js
View file

@ -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;

View file

@ -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 {