@airgap/serializer
Version:
The @airgap/serializer provides serializers used in AirGap applications.
56 lines • 2.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChunkedPayload = void 0;
var errors_1 = require("@airgap/coinlib-core/errors");
function isBufferArray(arg) {
return Array.isArray(arg) && arg.every(function (el) { return el instanceof Buffer; });
}
function isDecodedChunkedPayload(arg) {
// TODO: How can we detect if the interface changed?
if (!isObject(arg)) {
return false;
}
if (arg.currentPage === undefined || arg.total === undefined || arg.payload === undefined) {
return false;
}
return true;
}
function isObject(arg) {
return typeof arg === 'object';
}
function getIntFromBuffer(buffer) {
return parseInt(buffer.toString(), 10);
}
var ChunkedPayload = /** @class */ (function () {
function ChunkedPayload(currentPage, total, buffer) {
this.currentPage = currentPage;
this.total = total;
this.buffer = buffer;
}
ChunkedPayload.fromDecoded = function (object) {
if (!isDecodedChunkedPayload(object)) {
throw new errors_1.SerializerError(errors_1.SerializerErrorType.UNEXPECTED_PAYLOAD, "Object does not match \"Chunked serializer\" interface");
}
return new ChunkedPayload(object.currentPage, object.total, object.payload);
};
ChunkedPayload.fromEncoded = function (buf) {
if (!isBufferArray(buf)) {
throw new errors_1.SerializerError(errors_1.SerializerErrorType.UNEXPECTED_PAYLOAD, "Input value is not a buffer array");
}
if (buf.length !== 3) {
throw new errors_1.SerializerError(errors_1.SerializerErrorType.UNEXPECTED_PAYLOAD, "Input value does not have the right length");
}
// We know here that the buffer has the following signature
// [currentPage, totalPages, payload]: [Buffer, Buffer, Buffer]
var currentPage = getIntFromBuffer(buf[0]);
var total = getIntFromBuffer(buf[1]);
var payload = buf[2];
return new ChunkedPayload(currentPage, total, payload);
};
ChunkedPayload.prototype.asArray = function () {
return [this.currentPage.toString(), this.total.toString(), this.buffer];
};
return ChunkedPayload;
}());
exports.ChunkedPayload = ChunkedPayload;
//# sourceMappingURL=chunked-payload.js.map