magnitude-core
Version:
Magnitude e2e testing agent
40 lines (39 loc) • 1.66 kB
JavaScript
import { Image } from './image';
export async function observableDataToJson(data) {
if (data instanceof Image) {
return await data.toJson(); //return imageToJson(data);
}
if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
return { type: "primitive", content: data };
}
if (data === undefined) {
return undefined; // JSON.stringify will omit keys with this value or handle standalone undefined
}
if (data === null) {
return null;
}
if (Array.isArray(data)) {
// Filter out undefined items first, then map and process the rest.
return Promise.all(data
.filter(item => item !== undefined)
.map(item => observableDataToJson(item)));
}
if (typeof data === 'object') { // Known not to be null or array here
const processedObject = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
const value = data[key];
const processedValue = observableDataToJson(value);
// Only add the key to the new object if its processed value is not undefined
if (processedValue !== undefined) {
processedObject[key] = processedValue;
}
}
}
return processedObject;
}
// Fallback for any unexpected data types not covered by ObservableData.
// Returning undefined is consistent with how unrepresentable values are handled.
return undefined;
}
// TODO: Implement deserialization, and actually leverage serde for logging stuff