mnml/client/index.js
2018-09-18 17:26:39 +10:00

81 lines
1.9 KiB
JavaScript
Executable File

const { toast } = require('bulma-toast');
const fizzyText = require('./src/fizzy-text');
fizzyText('cryps');
const cbor = require('borc');
const assert = require('assert');
// Create WebSocket connection.
const ws = new WebSocket('ws://localhost:40000');
ws.binaryType = 'arraybuffer';
// handle account auth within the socket itself
// https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html
let account = null;
function error_toast(err) {
console.error(err);
return toast({
message: err,
type: "is-warning",
duration: 5000,
});
}
function account_login(res) {
[struct, account] = res;
account = account;
console.log(account);
return send({ method: 'cryp_spawn', params: { name: 'drake' }});
}
function new_cryp(cryp) {
console.log('got a new cryp');
}
const handlers = {
'cryp_spawn': new_cryp,
'account_login': account_login,
'account_create': account_login,
};
function on_message(event) {
// decode binary msg from server
const blob = new Uint8Array(event.data);
const res = cbor.decode(blob);
console.log(res);
// check for error and split into response type and data
if (res.err) return error_toast(res.err);
const { method, params } = res;
return handlers[method](params);
}
function send(msg) {
msg.token = account && account.token;
ws.send(cbor.encode(msg));
}
// Connection opened
ws.addEventListener('open', function (event) {
// send({ method: 'account_create', params: { name: 'ntr', password: 'grepgrepgrep' }});
send({ method: 'account_login', params: { name: 'ntr', password: 'grepgrepgrep' }});
});
// Listen for messages
ws.addEventListener('message', on_message);
ws.addEventListener('error', function (event) {
console.error('WebSocket error', event);
account = null;
});
ws.addEventListener('close', function (event) {
console.error('WebSocket closed', event);
account = null;
});