@wishcore/wish-sdk
Version:
Wish API for node. Used for building Wish Apps.
74 lines • 3.33 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RpcApp = void 0;
const sdk_1 = require("./sdk");
const wish_rpc_1 = require("@wishcore/wish-rpc");
const BSON = new (require('bson-buffer'))();
class RpcApp {
constructor(opts) {
this.opts = opts;
this.clients = {};
this.protocols = {};
this.connections = {};
Object.entries(opts.protocols).forEach(([name, protocol]) => {
this.server = new wish_rpc_1.Server();
this.server.insertMethods(protocol.handler || {});
this.protocols[name] = { server: this.server, online: protocol.online, offline: protocol.offline };
});
const app = new sdk_1.App({
corePort: opts.corePort || 9094,
name: opts.name,
protocols: Object.keys(opts.protocols),
});
this.wish = app;
app.on('frame', (peer, frame) => {
const msg = BSON.deserialize(frame);
if (msg.op) {
const protocol = this.protocols[peer.protocol];
if (!protocol) {
return console.log('Unhandled protocol', peer.protocol);
}
protocol.server.parse({ id: msg.id, op: msg.op, args: msg.args }, (msg) => {
return app.requestAsync('services.send', [peer, BSON.serialize(msg)]);
}, { peer }, this.connections[peer.toUrl()]);
return;
}
else {
this.clients[peer.toUrl()].messageReceived(msg);
}
});
app.on('online', (peer) => __awaiter(this, void 0, void 0, function* () {
const protocol = this.protocols[peer.protocol];
if (!protocol) {
return console.log('Unhandled protocol', peer.protocol);
}
this.connections[peer.toUrl()] = protocol.server.open();
const client = new wish_rpc_1.Client((msg) => {
app.send(peer, BSON.serialize(msg));
});
this.clients[peer.toUrl()] = client;
protocol.online(peer, client);
}));
app.on('offline', (peer) => {
const protocol = this.protocols[peer.protocol];
if (!protocol) {
return console.log('Unhandled protocol', peer.protocol);
}
protocol.server.close(this.connections[peer.toUrl()]);
delete this.connections[peer.toUrl()];
delete this.clients[peer.toUrl()];
protocol.offline(peer);
});
}
}
exports.RpcApp = RpcApp;
//# sourceMappingURL=rpc-app.js.map