@requestnetwork/multi-format
Version:
Multi-format for Request Network packages.
69 lines • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SerializableMultiFormat = void 0;
/**
* Class to serialize and deserialize multi-format data
* This class is meant to be inherited by all the multi-format
*/
class SerializableMultiFormat {
constructor(prefix, type) {
this.prefix = prefix;
this.type = type;
}
/**
* Checks if an object is a deserialized multi-format
*
* @param data object to check
* @returns true if the data is a deserialized multi-format
*/
isSerializableObject(data) {
return data.type === this.type && !!data.value;
}
/**
* Checks if a string is a serialized multi-format
*
* @param data string to check
* @returns true if the data is a serialized multi-format
*/
isDeserializableString(formattedData) {
return formattedData.slice(0, 2) === this.prefix;
}
/**
* Serializes a deserialized multi-format
*
* @param data object to serialize
* @returns the data as a serialized multi-format
*/
serialize(data) {
if (!this.isSerializableObject(data)) {
throw new Error('object is not a serializable object');
}
return `${this.prefix}${data.value}`;
}
/**
* Deserialized a multi-format string
*
* @param data string to deserialized
* @returns the data as a deserialized multi-format
*/
deserialize(formatted) {
if (!this.isDeserializableString(formatted)) {
throw new Error('string is not a serialized string');
}
return {
type: this.type,
value: this.removePrefix(formatted),
};
}
/**
* Removes prefix of a multi-format
*
* @param formattedData the formatted multi-format
* @returns the hash without the multi-format prefix
*/
removePrefix(formattedData) {
return formattedData.slice(2);
}
}
exports.SerializableMultiFormat = SerializableMultiFormat;
//# sourceMappingURL=serializable-multi-format.js.map