@golemio/pid
Version:
Golemio PID Module
57 lines • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisJsonParser = void 0;
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
class RedisJsonParser {
/**
* Parses a Redis JSON.GET response when multiple properties are requested.
* For multiple properties, the result is like: { "$.a": [valueA], "$.b": [valueB] }.
*
* @param json - The JSON string or object to parse.
* @param context - Additional context for error handling.
* @returns The parsed object with unwrapped values.
*/
static parse(json, context) {
let parsed;
try {
parsed = typeof json === "string" ? JSON.parse(json) : json;
}
catch (err) {
throw new golemio_errors_1.GeneralError(`Failed to parse Redis JSON with more properties`, context, err);
}
const obj = {};
for (const [key, value] of Object.entries(parsed)) {
const newKey = key.startsWith("$.") ? key.slice(2) : key;
if (Array.isArray(value)) {
obj[newKey] = value.length === 1 ? value[0] : value;
}
else {
obj[newKey] = value;
}
}
return obj;
}
/**
* Parses a Redis JSON.GET response when a single property is requested.
* Result for one property is like: [ [ ...value... ] ].
*
* @param json - The JSON string or object to parse.
* @param context - Additional context for error handling.
* @param property - The property name to extract.
* @returns An object with the extracted property.
*/
static parseSingle(json, context, property) {
try {
const parsed = typeof json === "string" ? JSON.parse(json) : json;
const value = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
return {
[property]: value,
};
}
catch (err) {
throw new golemio_errors_1.GeneralError(`Failed to parse Redis JSON with single property`, context, err);
}
}
}
exports.RedisJsonParser = RedisJsonParser;
//# sourceMappingURL=RedisJsonParser.js.map