All files / framework/relationships LazyLoader.ts

0% Statements 0/169
0% Branches 0/113
0% Functions 0/37
0% Lines 0/166

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { BaseModel } from '../models/BaseModel';
import { RelationshipConfig } from '../types/models';
import { RelationshipManager, RelationshipLoadOptions } from './RelationshipManager';
 
export interface LazyLoadPromise<T> extends Promise<T> {
  isLoaded(): boolean;
  getLoadedValue(): T | undefined;
  reload(options?: RelationshipLoadOptions): Promise<T>;
}
 
export class LazyLoader {
  private relationshipManager: RelationshipManager;
 
  constructor(relationshipManager: RelationshipManager) {
    this.relationshipManager = relationshipManager;
  }
 
  createLazyProperty<T>(
    instance: BaseModel,
    relationshipName: string,
    config: RelationshipConfig,
    options: RelationshipLoadOptions = {},
  ): LazyLoadPromise<T> {
    let loadPromise: Promise<T> | null = null;
    let loadedValue: T | undefined = undefined;
    let isLoaded = false;
 
    const loadRelationship = async (): Promise<T> => {
      if (loadPromise) {
        return loadPromise;
      }
 
      loadPromise = this.relationshipManager
        .loadRelationship(instance, relationshipName, options)
        .then((result: T) => {
          loadedValue = result;
          isLoaded = true;
          return result;
        })
        .catch((error) => {
          loadPromise = null; // Reset so it can be retried
          throw error;
        });
 
      return loadPromise;
    };
 
    const reload = async (newOptions?: RelationshipLoadOptions): Promise<T> => {
      // Clear cache for this relationship
      this.relationshipManager.invalidateRelationshipCache(instance, relationshipName);
 
      // Reset state
      loadPromise = null;
      loadedValue = undefined;
      isLoaded = false;
 
      // Load with new options
      const finalOptions = newOptions ? { ...options, ...newOptions } : options;
      return this.relationshipManager.loadRelationship(instance, relationshipName, finalOptions);
    };
 
    // Create the main promise
    const promise = loadRelationship() as LazyLoadPromise<T>;
 
    // Add custom methods
    promise.isLoaded = () => isLoaded;
    promise.getLoadedValue = () => loadedValue;
    promise.reload = reload;
 
    return promise;
  }
 
  createLazyPropertyWithProxy<T>(
    instance: BaseModel,
    relationshipName: string,
    config: RelationshipConfig,
    options: RelationshipLoadOptions = {},
  ): T {
    const lazyPromise = this.createLazyProperty<T>(instance, relationshipName, config, options);
 
    // For single relationships, return a proxy that loads on property access
    if (config.type === 'belongsTo' || config.type === 'hasOne') {
      return new Proxy({} as any, {
        get(target: any, prop: string | symbol) {
          // Special methods
          if (prop === 'then') {
            return lazyPromise.then.bind(lazyPromise);
          }
          if (prop === 'catch') {
            return lazyPromise.catch.bind(lazyPromise);
          }
          if (prop === 'finally') {
            return lazyPromise.finally.bind(lazyPromise);
          }
          if (prop === 'isLoaded') {
            return lazyPromise.isLoaded;
          }
          if (prop === 'reload') {
            return lazyPromise.reload;
          }
 
          // If already loaded, return the property from loaded value
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue();
            return loadedValue ? (loadedValue as any)[prop] : undefined;
          }
 
          // Trigger loading and return undefined for now
          lazyPromise.catch(() => {}); // Prevent unhandled promise rejection
          return undefined;
        },
 
        has(target: any, prop: string | symbol) {
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue();
            return loadedValue ? prop in (loadedValue as any) : false;
          }
          return false;
        },
 
        ownKeys(_target: any) {
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue();
            return loadedValue ? Object.keys(loadedValue as any) : [];
          }
          return [];
        },
      });
    }
 
    // For collection relationships, return a proxy array
    if (config.type === 'hasMany' || config.type === 'manyToMany') {
      return new Proxy([] as any, {
        get(target: any[], prop: string | symbol) {
          // Array methods and properties
          if (prop === 'length') {
            if (lazyPromise.isLoaded()) {
              const loadedValue = lazyPromise.getLoadedValue() as any[];
              return loadedValue ? loadedValue.length : 0;
            }
            return 0;
          }
 
          // Promise methods
          if (prop === 'then') {
            return lazyPromise.then.bind(lazyPromise);
          }
          if (prop === 'catch') {
            return lazyPromise.catch.bind(lazyPromise);
          }
          if (prop === 'finally') {
            return lazyPromise.finally.bind(lazyPromise);
          }
          if (prop === 'isLoaded') {
            return lazyPromise.isLoaded;
          }
          if (prop === 'reload') {
            return lazyPromise.reload;
          }
 
          // Array methods that should trigger loading
          if (
            typeof prop === 'string' &&
            [
              'forEach',
              'map',
              'filter',
              'find',
              'some',
              'every',
              'reduce',
              'slice',
              'indexOf',
              'includes',
            ].includes(prop)
          ) {
            return async (...args: any[]) => {
              const loadedValue = await lazyPromise;
              return (loadedValue as any)[prop](...args);
            };
          }
 
          // Numeric index access
          if (typeof prop === 'string' && /^\d+$/.test(prop)) {
            if (lazyPromise.isLoaded()) {
              const loadedValue = lazyPromise.getLoadedValue() as any[];
              return loadedValue ? loadedValue[parseInt(prop, 10)] : undefined;
            }
            // Trigger loading
            lazyPromise.catch(() => {});
            return undefined;
          }
 
          // If already loaded, delegate to the actual array
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue() as any[];
            return loadedValue ? (loadedValue as any)[prop] : undefined;
          }
 
          return undefined;
        },
 
        has(target: any[], prop: string | symbol) {
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue() as any[];
            return loadedValue ? prop in loadedValue : false;
          }
          return false;
        },
 
        ownKeys(_target: any[]) {
          if (lazyPromise.isLoaded()) {
            const loadedValue = lazyPromise.getLoadedValue() as any[];
            return loadedValue ? Object.keys(loadedValue) : [];
          }
          return [];
        },
      }) as T;
    }
 
    // Fallback to promise for other types
    return lazyPromise as any;
  }
 
  // Helper method to check if a value is a lazy-loaded relationship
  static isLazyLoaded(value: any): value is LazyLoadPromise<any> {
    return (
      value &&
      typeof value === 'object' &&
      typeof value.then === 'function' &&
      typeof value.isLoaded === 'function' &&
      typeof value.reload === 'function'
    );
  }
 
  // Helper method to await all lazy relationships in an object
  static async resolveAllLazy(obj: any): Promise<any> {
    if (!obj || typeof obj !== 'object') {
      return obj;
    }
 
    if (Array.isArray(obj)) {
      return Promise.all(obj.map((item) => this.resolveAllLazy(item)));
    }
 
    const resolved: any = {};
    const promises: Array<Promise<void>> = [];
 
    for (const [key, value] of Object.entries(obj)) {
      if (this.isLazyLoaded(value)) {
        promises.push(
          value.then((resolvedValue) => {
            resolved[key] = resolvedValue;
          }),
        );
      } else {
        resolved[key] = value;
      }
    }
 
    await Promise.all(promises);
    return resolved;
  }
 
  // Helper method to get loaded relationships without triggering loading
  static getLoadedRelationships(instance: BaseModel): Record<string, any> {
    const loaded: Record<string, any> = {};
 
    const loadedRelations = instance.getLoadedRelations();
    for (const relationName of loadedRelations) {
      const value = instance.getRelation(relationName);
      if (this.isLazyLoaded(value)) {
        if (value.isLoaded()) {
          loaded[relationName] = value.getLoadedValue();
        }
      } else {
        loaded[relationName] = value;
      }
    }
 
    return loaded;
  }
 
  // Helper method to preload specific relationships
  static async preloadRelationships(
    instances: BaseModel[],
    relationships: string[],
    relationshipManager: RelationshipManager,
  ): Promise<void> {
    await relationshipManager.eagerLoadRelationships(instances, relationships);
  }
 
  // Helper method to create lazy collection with advanced features
  createLazyCollection<T extends BaseModel>(
    instance: BaseModel,
    relationshipName: string,
    config: RelationshipConfig,
    options: RelationshipLoadOptions = {},
  ): LazyCollection<T> {
    return new LazyCollection<T>(
      instance,
      relationshipName,
      config,
      options,
      this.relationshipManager,
    );
  }
}
 
// Advanced lazy collection with pagination and filtering
export class LazyCollection<T extends BaseModel> {
  private instance: BaseModel;
  private relationshipName: string;
  private config: RelationshipConfig;
  private options: RelationshipLoadOptions;
  private relationshipManager: RelationshipManager;
  private loadedItems: T[] = [];
  private isFullyLoaded = false;
  private currentPage = 1;
  private pageSize = 20;
 
  constructor(
    instance: BaseModel,
    relationshipName: string,
    config: RelationshipConfig,
    options: RelationshipLoadOptions,
    relationshipManager: RelationshipManager,
  ) {
    this.instance = instance;
    this.relationshipName = relationshipName;
    this.config = config;
    this.options = options;
    this.relationshipManager = relationshipManager;
  }
 
  async loadPage(page: number = 1, pageSize: number = this.pageSize): Promise<T[]> {
    const offset = (page - 1) * pageSize;
 
    const pageOptions: RelationshipLoadOptions = {
      ...this.options,
      constraints: (query) => {
        let q = query.offset(offset).limit(pageSize);
        if (this.options.constraints) {
          q = this.options.constraints(q);
        }
        return q;
      },
    };
 
    const pageItems = (await this.relationshipManager.loadRelationship(
      this.instance,
      this.relationshipName,
      pageOptions,
    )) as T[];
 
    // Update loaded items if this is sequential loading
    if (page === this.currentPage) {
      this.loadedItems.push(...pageItems);
      this.currentPage++;
 
      if (pageItems.length < pageSize) {
        this.isFullyLoaded = true;
      }
    }
 
    return pageItems;
  }
 
  async loadMore(count: number = this.pageSize): Promise<T[]> {
    return this.loadPage(this.currentPage, count);
  }
 
  async loadAll(): Promise<T[]> {
    if (this.isFullyLoaded) {
      return this.loadedItems;
    }
 
    const allItems = (await this.relationshipManager.loadRelationship(
      this.instance,
      this.relationshipName,
      this.options,
    )) as T[];
 
    this.loadedItems = allItems;
    this.isFullyLoaded = true;
 
    return allItems;
  }
 
  getLoadedItems(): T[] {
    return [...this.loadedItems];
  }
 
  isLoaded(): boolean {
    return this.loadedItems.length > 0;
  }
 
  isCompletelyLoaded(): boolean {
    return this.isFullyLoaded;
  }
 
  async filter(predicate: (item: T) => boolean): Promise<T[]> {
    if (!this.isFullyLoaded) {
      await this.loadAll();
    }
    return this.loadedItems.filter(predicate);
  }
 
  async find(predicate: (item: T) => boolean): Promise<T | undefined> {
    // Try loaded items first
    const found = this.loadedItems.find(predicate);
    if (found) {
      return found;
    }
 
    // If not fully loaded, load all and search
    if (!this.isFullyLoaded) {
      await this.loadAll();
      return this.loadedItems.find(predicate);
    }
 
    return undefined;
  }
 
  async count(): Promise<number> {
    if (this.isFullyLoaded) {
      return this.loadedItems.length;
    }
 
    // For a complete count, we need to load all items
    // In a more sophisticated implementation, we might have a separate count query
    await this.loadAll();
    return this.loadedItems.length;
  }
 
  clear(): void {
    this.loadedItems = [];
    this.isFullyLoaded = false;
    this.currentPage = 1;
  }
}