@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
53 lines (52 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDataSchema = getDataSchema;
const getStringFormat_1 = require("./getStringFormat");
// Maximum depth to traverse the data structure to get the schema for improved performance
const maxDepth = 20;
// Maximum number of properties per level
const maxProperties = 100;
/**
* Get the schema of the data (for example http json body) as a schema.
*/
function getDataSchema(data, depth = 0) {
// If the data is not an object (or an array), return the type
if (typeof data !== "object") {
if (typeof data === "string") {
const format = (0, getStringFormat_1.getStringFormat)(data);
if (format) {
return { type: "string", format };
}
}
return { type: typeof data };
}
// typeof null is object, but we want to treat it as null
if (data === null) {
return { type: "null" };
}
if (Array.isArray(data)) {
return {
type: "array",
// Assume that the array is homogenous (for performance reasons)
items: data.length > 0 ? getDataSchema(data[0]) : undefined,
};
}
const schema = {
type: "object",
properties: {},
};
// If the depth is less than the maximum depth, get the schema for each property
if (depth < maxDepth) {
let propertiesCount = 0;
for (const key in data) {
if (propertiesCount >= maxProperties) {
break;
}
propertiesCount++;
if (Object.prototype.hasOwnProperty.call(data, key)) {
schema.properties[key] = getDataSchema(data[key], depth + 1);
}
}
}
return schema;
}