@dataql/node
Version:
DataQL core SDK for unified data management with MongoDB and GraphQL - Production Multi-Cloud Ready
82 lines (81 loc) • 2.73 kB
JavaScript
;
/**
* Utility functions for unique document creation
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExcludedFieldsForComparison = getExcludedFieldsForComparison;
exports.extractComparableFields = extractComparableFields;
exports.areFieldsMatching = areFieldsMatching;
/**
* Identifies which fields in a schema should be excluded from uniqueness comparison
* @param schema The schema object to analyze
* @returns Array of field names to exclude (ID fields and subdocument fields)
*/
function getExcludedFieldsForComparison(schema) {
const excludedFields = [];
for (const [key, field] of Object.entries(schema)) {
// Exclude ID fields
if (key === "id" || key === "_id" || key.toLowerCase().includes("id")) {
excludedFields.push(key);
continue;
}
// Exclude subdocument arrays
if (Array.isArray(field) &&
field.length > 0 &&
typeof field[0] === "object") {
excludedFields.push(key);
continue;
}
// Exclude nested objects (subdocuments)
if (typeof field === "object" &&
field !== null &&
!Array.isArray(field) &&
!field.type &&
!field.enum) {
excludedFields.push(key);
continue;
}
}
return excludedFields;
}
/**
* Extracts comparable fields from a document, excluding ID and subdocument fields
* @param document The document to extract fields from
* @param schema The schema to determine which fields to exclude
* @returns Object with only comparable fields
*/
function extractComparableFields(document, schema) {
const excludedFields = getExcludedFieldsForComparison(schema);
const comparableFields = {};
for (const [key, value] of Object.entries(document)) {
if (!excludedFields.includes(key)) {
comparableFields[key] = value;
}
}
return comparableFields;
}
/**
* Checks if two objects have matching field values
* @param obj1 First object to compare
* @param obj2 Second object to compare
* @returns True if all fields match, false otherwise
*/
function areFieldsMatching(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
// Check if they have the same number of keys
if (keys1.length !== keys2.length) {
return false;
}
// Check if all keys and values match
for (const key of keys1) {
if (!(key in obj2)) {
return false;
}
// Deep comparison for nested values
if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
return false;
}
}
return true;
}