@dataql/node
Version:
DataQL core SDK for unified data management with MongoDB and GraphQL - Production Multi-Cloud Ready
92 lines (91 loc) • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAgainstSchema = validateAgainstSchema;
function getTypeName(type) {
if (type === String)
return "string";
if (type === Number)
return "number";
if (type === Boolean)
return "boolean";
if (type === Date)
return "string"; // ISO string
if (typeof type === "string") {
// Support for SDK's type aliases
switch (type) {
case "String":
return "string";
case "Int":
return "number";
case "Number":
return "number";
case "Boolean":
return "boolean";
case "Date":
return "string";
case "ID":
return "string";
case "Decimal":
return "string";
default:
return typeof type;
}
}
return typeof type;
}
function validateAgainstSchema(schema, value, path = "") {
// Handle enum fields FIRST
if (typeof schema === "object" &&
schema !== null &&
Array.isArray(schema.enum)) {
if (typeof value !== "string") {
throw new Error(`${path} should be a string (enum)`);
}
if (!schema.enum.includes(value)) {
throw new Error(`${path} should be one of: ${schema.enum.join(", ")}`);
}
return;
}
if (Array.isArray(schema)) {
if (!Array.isArray(value))
throw new Error(`${path} should be an array`);
for (let i = 0; i < value.length; i++) {
validateAgainstSchema(schema[0], value[i], `${path}[${i}]`);
}
return;
}
if (typeof schema === "object" && schema !== null) {
if (typeof value !== "object" || value === null) {
throw new Error(`${path} should be an object`);
}
for (const key in schema) {
validateAgainstSchema(schema[key], value[key], path ? `${path}.${key}` : key);
}
return;
}
// Special case: Money type
if (schema === "Money") {
if (typeof value !== "object" ||
value === null ||
typeof value.amount !== "string" ||
typeof value.currency !== "string") {
throw new Error(`${path} should be an object with string amount and string currency fields (Money)`);
}
return;
}
// Special case: Geo type
if (schema === "Geo") {
if (typeof value !== "object" ||
value === null ||
typeof value.type !== "string" ||
!Array.isArray(value.coordinates)) {
throw new Error(`${path} should be an object with string type and array coordinates fields (Geo)`);
}
return;
}
// Primitive type check
const expectedType = getTypeName(schema);
if (typeof value !== expectedType) {
throw new Error(`${path} should be of type ${expectedType}`);
}
}