helene
Version:
Real-time Web Apps for Node.js
59 lines • 2.1 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientHttp = void 0;
const utils_1 = require("../utils");
const ejson_1 = require("../ejson");
class ClientHttp {
client;
protocol;
host;
uri;
constructor(client) {
this.client = client;
this.protocol = this.client.options.secure ? `https://` : `http://`;
if (this.client.options.port) {
this.host = `${this.protocol}${this.client.options.host}:${this.client.options.port}`;
}
else {
this.host = `${this.protocol}${this.client.options.host}`;
}
this.uri = `${this.host}/__h`;
}
async request(payload, resolve, reject) {
try {
// @ts-ignore
const data = await fetch(this.uri, {
method: 'POST',
headers: {
[utils_1.CLIENT_ID_HEADER_KEY]: this.client.uuid,
Accept: 'text/plain, */*',
'Content-Type': 'text/plain',
...(this.client.context.token
? { [utils_1.TOKEN_HEADER_KEY]: this.client.context.token }
: {}),
},
body: ejson_1.EJSON.stringify({
context: this.client.context,
payload,
}),
});
if (data.status !== 200) {
return reject(new Error(`${data.status} ${data.statusText}: ${JSON.stringify(await data.text())}`));
}
if (!resolve) {
return;
}
const response = await data.text();
const decoded = utils_1.Presentation.decode(response);
this.client.emit(utils_1.ClientEvents.INBOUND_MESSAGE, decoded);
if (decoded.type === utils_1.PayloadType.ERROR)
return reject(decoded);
resolve(decoded.result);
}
catch (error) {
return reject(error);
}
}
}
exports.ClientHttp = ClientHttp;
//# sourceMappingURL=client-http.js.map