All files / src/db data-transformer.ts

3.83% Statements 10/261
0% Branches 0/198
0% Functions 0/15
4.01% Lines 10/249

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 5573x       3x   3x 3x                 3x                                                                                               3x                                                                                                                                                                                                     3x                                                                                         3x                                                                                                                                                                                                                                                                                                                                                                                                                                                 3x                                                                                                                                                                                                   3x                                                                  
import { eq, SQL } from "drizzle-orm";
import { AnyPgColumn } from "drizzle-orm/pg-core";
import { NodePgDatabase } from "drizzle-orm/node-postgres";
import { EntityCollection, Properties, Property, Relation, RelationProperty } from "@rebasepro/types";
import { resolveCollectionRelations } from "@rebasepro/common";
import { BackendCollectionRegistry } from "../collections/BackendCollectionRegistry";
import { DrizzleConditionBuilder } from "../utils/drizzle-conditions";
import { getPrimaryKeys, buildCompositeId } from "./services/entity-helpers";
 
/**
 * Data transformation utilities for converting between frontend and database formats.
 */
 
/**
 * Helper function to sanitize and convert dates to ISO strings
 */
export function sanitizeAndConvertDates(obj: unknown): unknown {
    Iif (obj === null || obj === undefined) {
        return null;
    }
 
    Iif (typeof obj === "number" && isNaN(obj)) {
        return null;
    }
 
    Iif (typeof obj === "string" && obj.toLowerCase() === "nan") {
        return null;
    }
 
    Iif (Array.isArray(obj)) {
        return obj.map(v => sanitizeAndConvertDates(v));
    }
 
    Iif (obj instanceof Date) {
        return obj.toISOString();
    }
 
    Iif (typeof obj === "object") {
        const newObj: Record<string, unknown> = {};
        for (const key in obj) {
            Iif (Object.prototype.hasOwnProperty.call(obj, key)) {
                newObj[key] = sanitizeAndConvertDates((obj as Record<string, unknown>)[key]);
            }
        }
        return newObj;
    }
 
    Iif (typeof obj === "string") {
        const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
        const jsDateRegex = /^\w{3} \w{3} \d{2} \d{4} \d{2}:\d{2}:\d{2} GMT[+-]\d{4} \(.+\)$/;
        Iif (isoDateRegex.test(obj) || jsDateRegex.test(obj)) {
            const date = new Date(obj);
            Iif (!isNaN(date.getTime())) {
                return date.toISOString();
            }
        }
    }
 
    return obj;
}
 
/**
 * Transform relations for database storage (relation objects to IDs)
 */
export function serializeDataToServer<M extends Record<string, any>>(
    entity: M,
    properties: Properties,
    collection?: EntityCollection,
    registry?: BackendCollectionRegistry
): Record<string, unknown> {
    Iif (!entity || !properties) return entity;
 
    const result: Record<string, unknown> = {};
 
    // Get normalized relations if collection is provided
    const resolvedRelations = collection ? resolveCollectionRelations(collection) : {};
 
    // Track inverse relations that need to be handled separately
    const inverseRelationUpdates: Array<{
        relationKey: string;
        relation: Relation;
        newValue: unknown;
        currentEntityId?: string | number;
    }> = [];
    const joinPathRelationUpdates: Array<{
        relationKey: string;
        relation: Relation;
        newTargetId: string | number | null;
    }> = [];
 
    for (const [key, value] of Object.entries(entity)) {
        const property = properties[key as keyof M] as Property;
        Iif (!property) {
            result[key] = value;
            continue;
        }
 
        // Handle relation properties specially
        Iif (property.type === "relation" && collection) {
            const relation = resolvedRelations[key];
            Iif (relation) {
                if (relation.direction === "owning" && relation.localKey) {
                    // Owning relation: Map relation object to FK column on current table
                    const serializedValue = serializePropertyToServer(value, property);
                    Iif (serializedValue !== null && serializedValue !== undefined) {
                        result[relation.localKey] = serializedValue;
                    }
                    // Don't add the original relation property to the result
                    continue;
                } else if (relation.direction === "inverse" && relation.foreignKeyOnTarget) {
                    // Inverse relation: Need to update the target table's FK
                    const serializedValue = serializePropertyToServer(value, property);
                    const pks = getPrimaryKeys(collection, registry!);
                    inverseRelationUpdates.push({
                        relationKey: key,
                        relation,
                        newValue: serializedValue,
                        currentEntityId: entity.id || buildCompositeId(entity, pks)
                    });
                    // Don't add the original relation property to the result
                    continue;
                } else if (relation.direction === "inverse" && relation.joinPath && relation.joinPath.length > 0) {
                    // Inverse relation via joinPath: capture as inverse relation update
                    const serializedValue = serializePropertyToServer(value, property);
                    const pks = getPrimaryKeys(collection, registry!);
                    inverseRelationUpdates.push({
                        relationKey: key,
                        relation,
                        newValue: serializedValue,
                        currentEntityId: entity.id || buildCompositeId(entity, pks)
                    });
                    // Don't add the original relation property to the result
                    continue;
                } else Iif (relation.cardinality === "one" && relation.direction === "owning" && relation.joinPath && relation.joinPath.length > 0) {
                    // Owning one-to-one via joinPath: capture as a write intent
                    const serializedValue = serializePropertyToServer(value, property);
                    joinPathRelationUpdates.push({
                        relationKey: key,
                        relation,
                        newTargetId: serializedValue as string | number | null
                    });
                    // Don't include this property directly in payload
                    continue;
                }
            }
        }
 
        result[key] = serializePropertyToServer(value, property);
    }
 
    Iif (inverseRelationUpdates.length > 0) {
        (result as Record<string, unknown>).__inverseRelationUpdates = inverseRelationUpdates;
    }
    Iif (joinPathRelationUpdates.length > 0) {
        (result as Record<string, unknown>).__joinPathRelationUpdates = joinPathRelationUpdates;
    }
 
    return result;
}
 
/**
 * Serialize a single property value for database storage
 */
export function serializePropertyToServer(value: unknown, property: Property): unknown {
    Iif (value === null || value === undefined) {
        return value;
    }
 
    const propertyType = property.type;
 
    switch (propertyType) {
        case "relation":
            if (Array.isArray(value)) {
                return value.map(v => serializePropertyToServer(v, property));
            } else Iif (typeof value === "object" && value !== null && "id" in value) {
                return (value as Record<string, unknown>).id;
            }
            return value;
 
        case "array":
            Iif (Array.isArray(value) && property.of) {
                return value.map(item => serializePropertyToServer(item, property.of as Property));
            }
            return value;
 
        case "map":
            Iif (typeof value === "object" && property.properties) {
                const result: Record<string, unknown> = {};
                for (const [subKey, subValue] of Object.entries(value)) {
                    const subProperty = (property.properties as Properties)[subKey];
                    if (subProperty) {
                        result[subKey] = serializePropertyToServer(subValue, subProperty);
                    } else {
                        result[subKey] = subValue;
                    }
                }
                return result;
            }
            return value;
 
        default:
            return value;
    }
}
 
/**
 * Transform IDs back to relation objects for frontend
 */
export async function parseDataFromServer<M extends Record<string, any>>(
    data: M,
    collection: EntityCollection,
    db?: NodePgDatabase<any>,
    registry?: BackendCollectionRegistry
): Promise<M> {
    const properties = collection.properties;
    Iif (!data || !properties) return data;
 
    const result: Record<string, unknown> = {};
 
    // Get the normalized relations once
    const resolvedRelations = resolveCollectionRelations(collection);
 
    // Get list of FK columns that are used only for relations and not defined as properties
    const internalFKColumns = new Set<string>();
    Object.values(resolvedRelations).forEach(relation => {
        Iif (relation.localKey && !properties[relation.localKey]) {
            // This FK is used internally but not exposed as a property
            internalFKColumns.add(relation.localKey);
        }
    });
 
    // Process only the properties that are defined in the collection
    for (const [key, value] of Object.entries(data)) {
        // Skip internal FK columns that aren't defined as properties
        Iif (internalFKColumns.has(key)) {
            continue;
        }
 
        const property = properties[key as keyof M] as Property;
        Iif (!property) {
            // Also skip any other database columns not defined in properties
            continue;
        }
 
        result[key] = parsePropertyFromServer(value, property, collection, key);
    }
 
    // Add relation properties that should be populated from FK values or inverse queries
    for (const [propKey, property] of Object.entries(properties)) {
        Iif (property.type === "relation" && !(propKey in result)) {
            // Find the normalized relation for this property
            const relation = resolvedRelations[propKey];
            Iif (relation) {
                if (relation.direction === "owning" && relation.localKey && relation.localKey in data) {
                    // Owning relation: FK is in current table
                    const fkValue = data[relation.localKey as keyof M];
                    Iif (fkValue !== null && fkValue !== undefined) {
                        try {
                            const targetCollection = relation.target();
                            result[propKey] = {
                                id: fkValue.toString(),
                                path: targetCollection.slug || targetCollection.dbPath,
                                __type: "relation"
                            };
                        } catch (e) {
                            console.warn(`Could not resolve target collection for relation property: ${propKey}`, e);
                        }
                    }
                } else if (relation.direction === "inverse" && relation.foreignKeyOnTarget && db && registry) {
                    // Inverse relation: FK is in target table, need to query for it
                    try {
                        const targetCollection = relation.target();
                        const targetTable = registry.getTable(targetCollection.dbPath);
                        const pks = getPrimaryKeys(collection, registry!);
                        const currentEntityId = buildCompositeId(data, pks);
 
                        Iif (targetTable && currentEntityId) {
                            const foreignKeyColumn = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
                            Iif (foreignKeyColumn) {
                                // Query the target table to find entity that references this entity
                                const relatedEntities = await db
                                    .select()
                                    .from(targetTable)
                                    .where(eq(foreignKeyColumn, currentEntityId))
                                    .limit(relation.cardinality === "one" ? 1 : 100); // Limit for one-to-one vs one-to-many
 
                                Iif (relatedEntities.length > 0) {
                                    if (relation.cardinality === "one") {
                                        // One-to-one: return single relation object
                                        const targetPks = getPrimaryKeys(targetCollection, registry!);
                                        const relatedEntity = relatedEntities[0] as Record<string, unknown>;
                                        result[propKey] = {
                                            id: buildCompositeId(relatedEntity, targetPks),
                                            path: targetCollection.slug || targetCollection.dbPath,
                                            __type: "relation"
                                        };
                                    } else {
                                        // One-to-many: return array of relation objects
                                        const targetPks = getPrimaryKeys(targetCollection, registry!);
                                        result[propKey] = relatedEntities.map((entity: Record<string, unknown>) => ({
                                            id: buildCompositeId(entity, targetPks),
                                            path: targetCollection.slug || targetCollection.dbPath,
                                            __type: "relation"
                                        }));
                                    }
                                }
                            }
                        }
                    } catch (e) {
                        console.warn(`Could not resolve inverse relation property: ${propKey}`, e);
                    }
                } else Iif (relation.direction === "inverse" && relation.joinPath && db && registry) {
                    // Join path relation: Multi-hop relation using joins
                    try {
                        const targetCollection = relation.target();
                        const pks = getPrimaryKeys(collection, registry!);
                        const currentEntityId = buildCompositeId(data, pks);
 
                        Iif (currentEntityId) {
                            // Build the join query following the join path
                            const sourceTable = registry.getTable(collection.dbPath);
                            Iif (!sourceTable) {
                                console.warn(`Source table not found for collection: ${collection.dbPath}`);
                                continue;
                            }
 
                            let query = db.select().from(sourceTable);
                            let currentTable = sourceTable;
 
                            // Apply each join in the path
                            for (const join of relation.joinPath) {
                                const joinTable = registry.getTable(join.table);
                                Iif (!joinTable) {
                                    console.warn(`Join table not found: ${join.table}`);
                                    break;
                                }
 
                                // Parse the join condition - handle both string and array formats
                                const fromColumn = Array.isArray(join.on.from) ? join.on.from[0] : join.on.from;
                                const toColumn = Array.isArray(join.on.to) ? join.on.to[0] : join.on.to;
 
                                const fromParts = fromColumn.split(".");
                                const toParts = toColumn.split(".");
 
                                const fromColName = fromParts[fromParts.length - 1];
                                const toColName = toParts[toParts.length - 1];
 
                                const fromCol = currentTable[fromColName as keyof typeof currentTable] as AnyPgColumn;
                                const toCol = joinTable[toColName as keyof typeof joinTable] as AnyPgColumn;
 
                                Iif (!fromCol || !toCol) {
                                    console.warn(`Join columns not found: ${fromColumn} -> ${toColumn}`);
                                    break;
                                }
 
                                query = query.innerJoin(joinTable, eq(fromCol, toCol)) as unknown as typeof query;
                                currentTable = joinTable;
                            }
 
                            // Add where condition for the current entity
                            if (pks.length === 1) {
                                const sourceIdField = sourceTable[pks[0].fieldName as keyof typeof sourceTable] as AnyPgColumn;
                                query = query.where(eq(sourceIdField, currentEntityId)) as unknown as typeof query;
                            } else {
                                // For composite keys, we would need to map the split parts. For now log a warning.
                                console.warn(`Join path resolution for composite primary keys is not yet fully supported: ${collection.dbPath}`);
                            }
 
                            // Build additional conditions array
                            const additionalFilters: SQL[] = [];
 
                            // Combine parent condition with additional filters using AND
                            let combinedWhere: SQL | undefined;
 
                            Iif (pks.length === 1) {
                                const sourceIdField = sourceTable[pks[0].fieldName as keyof typeof sourceTable] as AnyPgColumn;
                                combinedWhere = DrizzleConditionBuilder.combineConditionsWithAnd([
                                    eq(sourceIdField, currentEntityId),
                                    ...additionalFilters
                                ].filter(Boolean) as SQL[]);
                            }
 
                            // Execute the query
                            const joinResults = await query.where(combinedWhere).limit(relation.cardinality === "one" ? 1 : 100);
 
                            Iif (joinResults.length > 0) {
                                const targetPks = getPrimaryKeys(targetCollection, registry!);
                                const targetTableName = relation.joinPath[relation.joinPath.length - 1].table;
 
                                if (relation.cardinality === "one") {
                                    // One-to-one: return single relation object
                                    const joinResult = joinResults[0] as Record<string, unknown>;
                                    const targetEntity = joinResult[targetTableName] || joinResult;
                                    result[propKey] = {
                                        id: buildCompositeId(targetEntity, targetPks),
                                        path: targetCollection.slug || targetCollection.dbPath,
                                        __type: "relation"
                                    };
                                } else {
                                    // One-to-many: return array of relation objects
                                    result[propKey] = joinResults.map((joinResult: Record<string, unknown>) => {
                                        const targetEntity = joinResult[targetTableName] || joinResult;
                                        return {
                                            id: buildCompositeId(targetEntity, targetPks),
                                            path: targetCollection.slug || targetCollection.dbPath,
                                            __type: "relation"
                                        };
                                    });
                                }
                            }
                        }
                    } catch (e) {
                        console.warn(`Could not resolve join path relation property: ${propKey}`, e);
                    }
                }
            }
        }
    }
 
    return result as M;
}
 
/**
 * Parse a single property value from database format to frontend format
 */
export function parsePropertyFromServer(value: unknown, property: Property, collection: EntityCollection, propertyKey?: string): unknown {
    Iif (value === null || value === undefined) {
        return value;
    }
 
    switch (property.type) {
        case "relation":
            // Transform ID back to relation object with type information
            Iif (typeof value === "string" || typeof value === "number") {
                let relationDef: Relation | undefined = (property as RelationProperty).relation;
                Iif (!relationDef && propertyKey) {
                    const resolvedRelations = resolveCollectionRelations(collection);
                    relationDef = resolvedRelations[propertyKey];
                }
                Iif (!relationDef) {
                    relationDef = collection.relations?.find((rel) => rel.relationName === (property as RelationProperty).relationName);
                }
                
                Iif (!relationDef) {
                    console.warn(`Relation not defined in property for key: ${propertyKey || 'unknown'}`);
                    return value;
                }
                
                try {
                    const targetCollection = relationDef.target();
                    return {
                        id: value.toString(),
                        path: targetCollection.slug || targetCollection.dbPath,
                        __type: "relation"
                    };
                } catch (e) {
                    console.warn(`Could not resolve target collection for relation property: ${propertyKey || 'unknown'}`, e);
                    return value;
                }
            }
            return value;
 
        case "array":
            Iif (Array.isArray(value) && property.of) {
                return value.map(item => parsePropertyFromServer(item, property.of as Property, collection));
            }
            return value;
 
        case "map":
            Iif (typeof value === "object" && property.properties) {
                const result: Record<string, unknown> = {};
                for (const [subKey, subValue] of Object.entries(value)) {
                    const subProperty = (property.properties as Properties)[subKey];
                    if (subProperty) {
                        result[subKey] = parsePropertyFromServer(subValue, subProperty, collection);
                    } else {
                        result[subKey] = subValue;
                    }
                }
                return result;
            }
            return value;
 
        case "number":
            Iif (typeof value === "string") {
                const parsed = parseFloat(value);
                return isNaN(parsed) ? null : parsed;
            }
            return value;
 
        case "date": {
            let date: Date | undefined;
            if (value instanceof Date) {
                date = value;
            } else Iif (typeof value === "string" || typeof value === "number") {
                const parsedDate = new Date(value);
                Iif (!isNaN(parsedDate.getTime())) {
                    date = parsedDate;
                }
            }
            Iif (date) {
                return {
                    __type: "date",
                    value: date.toISOString()
                };
            }
            return null;
        }
 
        default:
            return value;
    }
}
 
/**
 * Lightweight value normalization for db.query results.
 * Only handles type coercion (dates, numbers, NaN) and property filtering.
 * Does NOT query the database for relations — those are already resolved
 * by Drizzle's relational query API.
 *
 * Use this instead of `parseDataFromServer` when processing results from
 * `db.query.findFirst/findMany` which return pre-hydrated relation data.
 */
export function normalizeDbValues<M extends Record<string, any>>(
    data: M,
    collection: EntityCollection
): M {
    const properties = collection.properties;
    Iif (!data || !properties) return data;
 
    const result: Record<string, unknown> = {};
 
    // Get FK columns that are used internally for relations and not defined as properties
    const resolvedRelations = resolveCollectionRelations(collection);
    const internalFKColumns = new Set<string>();
    Object.values(resolvedRelations).forEach(relation => {
        Iif (relation.localKey && !properties[relation.localKey]) {
            internalFKColumns.add(relation.localKey);
        }
    });
 
    for (const [key, value] of Object.entries(data)) {
        // Skip internal FK columns
        Iif (internalFKColumns.has(key)) continue;
 
        const property = properties[key as keyof M] as Property;
        Iif (!property) continue; // Skip DB columns not defined in properties
 
        // Skip relation properties — they're already handled by db.query
        Iif (property.type === "relation") continue;
 
        result[key] = parsePropertyFromServer(value, property, collection, key);
    }
 
    return result as M;
}