Convert to WebSockets #1

Open
NBTX wants to merge 1 commit from NBTX/remote-client:master into master
4 changed files with 52 additions and 15 deletions
Showing only changes of commit dc28474668 - Show all commits

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
node_modules/

View file

@ -1,10 +1,38 @@
const fetch = require('node-fetch');
const WebSocket = require('ws');
const { uuid = v4 } = require('uuid');
/**
* @class Client
* @param {Number} port
*/
function Client({ port }){
function Client({ port, host }) {
let ws;
let pendingOperations = {};
/**
* @method open
*/
this.open = () => {
ws = new WebSocket(`ws://${host ?? 'localhost'}:${port}`);
ws.addEventListener('message', (message) => {
let data = JSON.parse(message);
let pendingOperation = pendingOperations[data.id];
if (!data.error)
pendingOperation[0](data.response);
else
pendingOperation[1](data.response);
delete pendingOperations[data.id];
});
};
/**
* @method close
*/
this.close = () => ws.close();
/**
* @method execute
* @param {Function} _function
@ -12,14 +40,16 @@ function Client({ port }){
* @return {Promise<String>}
*/
this.execute = (_function, params) =>
new Promise((resolve, reject) =>
fetch(`http://localhost:${port}`, {
method: 'POST',
body: `(${_function})(${JSON.stringify(params)})`
}).then(res => res.text().then(body => ({
200: resolve,
400: reject
})[res.status](body)).catch(reject)).catch(reject));
new Promise((resolve, reject) => {
if (ws.readyState !== ws.OPEN)
reject();
let id = uuid();
pendingOperations[id] = [resolve, reject];
ws.send(JSON.stringify({
id, payload: `(${_function})(${JSON.stringify(params)})`
}));
});
}
module.exports = Client;

View file

@ -2,6 +2,7 @@
"name": "@thornhill-corp/remote-client",
"version": "0.1.0",
"dependencies": {
"node-fetch": "^2.6.1"
"uuid": "^8.3.2",
"ws": "^7.4.3"
}
}

View file

@ -2,7 +2,12 @@
# yarn lockfile v1
node-fetch@^2.6.1:
version "2.6.1"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052"
integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==
uuid@^8.3.2:
version "8.3.2"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
ws@^7.4.3:
version "7.4.3"
resolved "https://registry.yarnpkg.com/ws/-/ws-7.4.3.tgz#1f9643de34a543b8edb124bdcbc457ae55a6e5cd"
integrity sha512-hr6vCR76GsossIRsr8OLR9acVVm1jyfEWvhbNjtgPOrfvAlKzvyeg/P6r8RuDjRyrcQoPQT7K0DGEPc7Ae6jzA==