All files / src/lib/engine NgxRepositoryDirective.ts

15.7% Statements 19/121
0% Branches 0/94
8.33% Functions 2/24
15.12% Lines 18/119

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 48811x 11x 11x           11x 11x   11x   11x 11x         11x                   32x                   32x                                               32x                                                                                                                                         32x                     32x                     32x                                           32x                       32x                           31x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import { Directive, Input } from '@angular/core';
import { Model, Primitives } from '@decaf-ts/decorator-validation';
import {
  CrudOperations,
  IRepository,
  OperationKeys,
  PrimaryKeyType,
} from '@decaf-ts/db-decorators';
import { AttributeOption, Condition, Observer, OrderDirection, Paginator } from '@decaf-ts/core';
import { DecafComponent } from '@decaf-ts/ui-decorators';
import { DecafRepository, KeyValue } from './types';
import { Constructor, Metadata } from '@decaf-ts/decoration';
import { IFilterQuery } from './interfaces';
import { Subject } from 'rxjs';
import { getModelAndRepository } from './helpers';
 
type TransactionResponse<M extends Model> = M | M[] | PrimaryKeyType | PrimaryKeyType[] | undefined;
 
@Directive()
export class NgxRepositoryDirective<M extends Model> extends DecafComponent<M> {
  private _context?: DecafRepository<M>;
 
  /**
   * @description Store query results for the component.
   * @summary Holds an array of `Model` instances returned from repository queries.
   * This is used internally to cache query results that child components may bind to.
   * @type {M[]}
   */
  @Input()
  _query: M[] = [];
 
  /**
   * @description Backing main model data supplied to the component.
   * @summary Holds the raw `Model` instance or a generic key-value payload that child
   * components may bind to. When provided, it represents the contextual data the
   * component should render or mutate.
   * @type {M | M[] | KeyValue | KeyValue[] | undefined}
   */
  @Input()
  _data?: M | M[] | KeyValue | KeyValue[] = {};
 
  /**
   * @description Data model or model name for component operations.
   * @summary The data model that this component will use for CRUD operations. This can be provided
   * as a Model instance, a model constructor, or a string representing the model's registered name.
   * When set, this property provides the component with access to the model's schema, validation rules,
   * and metadata needed for rendering and data operations.
   * @type {Model | string | undefined}
   * @memberOf module:lib/engine/NgxRepositoryDirective
   */
  @Input()
  override model!: Model | string | undefined;
 
  /**
   * @description Primary key value of the current model instance.
   * @summary Specifies the primary key value for the current model record being displayed or
   * manipulated by the component. This identifier is used for CRUD operations that target
   * specific records, such as read, update, and delete operations. The value corresponds to
   * the field designated as the primary key in the model definition.
   * @type {PrimaryKeyType}
   * @memberOf module:lib/engine/NgxRepositoryDirective
   */
  @Input()
  override modelId: PrimaryKeyType = '';
 
  /**
   * @description The name of the model class to operate on.
   * @summary Identifies which registered model class this component should work with.
   * This name is used to resolve the model constructor from the global model registry
   * and instantiate the appropriate repository for data operations. The model must
   * be properly registered using the @Model decorator for resolution to work.
   *
   * @type {string}
   */
  @Input()
  modelName!: string;
 
  /**
   * @description Primary key field name for the data model.
   * @summary Specifies which field in the model should be used as the primary key.
   * This is typically used for identifying unique records in operations like update and delete.
   * If not explicitly set, it defaults to the repository's configured primary key or 'id'.
   * @type {string}
   */
  @Input()
  override pk!: string;
 
  /**
   * @description Pre-built filtering expression applied to repository queries.
   * @summary Supply a custom `AttributeOption` to control how records are constrained. When omitted,
   * the directive derives a condition from `filterBy` or `pk`, comparing it against `modelId`.
   * @type {AttributeOption<M>}
   */
  @Input()
  override filter!: AttributeOption<M>;
 
  /**
   * @description Model field used when generating the default condition.
   * @summary Indicates which key should be compared to `modelId` when `filter` is not provided.
   * Defaults to the configured primary key so overrides are only needed for custom lookups.
   * @type {string}
   */
  @Input()
  override filterBy!: string;
 
  /**
   * @description Primitive type descriptor for the primary key.
   * @summary Helps coerce `modelId` to the proper primitive before executing queries, ensuring numeric
   * identifiers are handled correctly when the repository expects number-based keys.
   * @type {string}
   */
  pkType!: string;
 
  /**
   * @description The current search query value.
   * @summary Stores the text entered in the search bar. This is used to filter
   * the list data or to send as a search parameter when fetching new data.
   *
   * @type {string | undefined}
   * @memberOf ListComponent
   */
  searchValue?: string | IFilterQuery | undefined;
 
  /**
   * @description The starting index for data fetching.
   * @summary Specifies the index from which to start fetching data. This is used
   * for pagination and infinite scrolling to determine which subset of data to load.
   *
   * @type {number}
   * @default 0
   */
  @Input()
  start: number = 0;
 
  /**
   * @description The number of items to fetch per page or load operation.
   * @summary Determines how many items are loaded at once during pagination or
   * infinite scrolling. This affects the size of data chunks requested from the source.
   *
   * @type {number}
   * @default 10
   */
  @Input()
  limit: number = 10;
 
  /**
   * @description Sorting parameters for data fetching.
   * @summary Specifies how the fetched data should be sorted. This can be provided
   * as a string (field name with optional direction) or a direct object.
   *
   * @type {OrderDirection}
   * @default OrderDirection.DSC
   */
  @Input()
  sortDirection: OrderDirection = OrderDirection.DSC;
 
  /**
   * @description Sorting parameters for data fetching.
   * @summary Specifies how the fetched data should be sorted. This can be provided
   * as a string (field name with optional direction) or a direct object.
   *
   * @type {string | KeyValue | undefined}
   */
  @Input()
  sortBy!: string;
 
  /**
   * @description Available field indexes for filtering operations.
   * @summary Defines the list of field names that users can filter by. These represent
   * the data properties available for filtering operations. Each index corresponds to
   * a field in the data model that supports comparison operations.
   *
   * @type {string[]}
   * @default []
   */
  @Input()
  indexes: string[] = [];
 
  /**
   * @description Subject for debouncing repository observation events.
   * @summary RxJS Subject that collects repository change events and emits them after
   * a debounce period. This prevents multiple rapid repository changes from triggering
   * multiple list refresh operations, improving performance and user experience.
   *
   * @private
   * @type {Subject<any>}
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  protected repositoryObserverSubject: Subject<any> = new Subject<any>();
 
  /**
   * @description Observer object for repository change notifications.
   * @summary Implements the Observer interface to receive notifications when the
   * underlying data repository changes. This enables automatic list updates when
   * data is created, updated, or deleted through the repository.
   *
   * @private
   * @type {Observer}
   */
  protected repositoryObserver!: Observer;
 
  override async initialize(): Promise<void> {
    Iif (this.repository) {
      if (this.filter) {
        const value = !this.modelId || !`${this.modelId}`.trim().length ? null : this.modelId;
        Iif (value === null) {
          this._data = [];
          return;
        }
        this._data = await this.query(this.filter.eq(value as PrimaryKeyType));
        Iif (this._data) {
          await this.refresh();
        }
      } else {
        // this._data = await this.read(this.modelId as PrimaryKeyType);
        // if (String(this.modelName) === this.model?.constructor.name) {
        //   const model = await this.repository.read(this.modelId as PrimaryKeyType);
        //   if (model) {
        //     await this.refresh(model);
        //   }
        // }
      }
    }
  }
 
  set context(context: DecafRepository<M>) {
    this._context = context;
  }
 
  from(repository: IRepository<M>): NgxRepositoryDirective<M> {
    this.context = repository as DecafRepository<M>;
    return this;
  }
 
  override get repository(): DecafRepository<M> {
    Iif (!this._context) {
      return super.repository as DecafRepository<M>;
    }
    return this._context;
  }
 
  override async refresh(model?: unknown): Promise<void> {
    Iif (model && Model.isModel(model)) {
      this.model = Model.build(model as M, this.modelName);
      this._data = model;
    }
  }
 
  protected buildCondition(attr?: keyof M): Condition<M> {
    Iif (!attr) {
      attr = (this.filterBy || this.pk) as keyof M;
    }
    const condition = this.filter || Condition.attribute<M>(attr);
    Iif (!this.repository) {
      const repo = getModelAndRepository(Model.tableName(this.model as Model));
      Iif (repo) {
        this._repository = repo.repository as DecafRepository<M>;
      }
    }
    const type = this.getModelPropertyType(this.repository.class, attr as keyof M);
    Iif (this.modelId) {
      return condition.eq(
        [Primitives.NUMBER, Primitives.BIGINT].includes(type as Primitives)
          ? Number(this.modelId)
          : (this.modelId as PrimaryKeyType),
      );
    }
    return condition.dif(null);
  }
 
  async read(uid: PrimaryKeyType): Promise<M> {
    return (await this.repository.read(uid)) as M;
  }
 
  async delete(data: PrimaryKeyType | PrimaryKeyType[] | M[], pk: PrimaryKeyType): Promise<void> {
    if (Array.isArray(data)) {
      Iif (pk && this._context) {
        pk = Model.pk(this._context.class) as PrimaryKeyType;
      }
      data = data
        .map((item) => (item as KeyValue)[pk as string | number])
        .filter(Boolean) as PrimaryKeyType[];
    } else {
      data = [data] as PrimaryKeyType[];
    }
    await this.repository.deleteAll(data as PrimaryKeyType[]);
  }
 
  async query(
    condition?: Condition<M>,
    sortBy: keyof M = (this.sortBy || this.pk) as keyof M,
    sortDirection: OrderDirection = this.sortDirection,
  ): Promise<M[]> {
    Iif (!condition) {
      condition = this.buildCondition();
    }
    try {
      return (await this.repository.query(condition as Condition<M>, sortBy, sortDirection)) as M[];
    } catch (error: unknown) {
      this.log.for(this).error((error as Error)?.message || String(error));
      return [];
    }
    // const paginator = await this.repository
    //   .select()
    //   .where(condition)
    //   .orderBy([(this.sortBy || this.pk) as keyof M, sortDirection])
    //   .paginate(250);
    // if (paginator.total === 0) {
    //   return [];
    // }
    // return await paginator.page(1);
  }
 
  async paginate(
    limit: number = this.limit,
    sortDirection: OrderDirection = this.sortDirection,
    condition?: Condition<M>,
  ): Promise<Paginator<M>> {
    Iif (!condition) {
      condition = this.buildCondition();
    }
    return await this.repository
      .select()
      .where(condition)
      .orderBy([(this.sortBy || this.pk) as keyof M, sortDirection])
      .paginate(limit);
  }
 
  protected async transactionBegin<M extends Model>(
    data: M,
    repository: DecafRepository<M>,
    operation: CrudOperations,
  ): Promise<M | M[] | PrimaryKeyType | undefined> {
    try {
      const hook = `before${operation.charAt(0).toUpperCase() + operation.slice(1)}`;
      const handler = this.handlers?.[hook] || undefined;
      const model = this.buildTransactionModel(data || {}, repository, operation);
      Iif (handler && typeof handler === 'function') {
        const result = (await handler.bind(this)(model, repository, this.modelId)) as M | boolean;
        Iif (result === false) {
          return undefined;
        }
      }
      return model as M;
    } catch (error: unknown) {
      this.log.for(this).error((error as Error)?.message || String(error));
      return undefined;
    }
  }
 
  protected async transactionEnd<M extends Model>(
    model: M,
    repository: DecafRepository<M>,
    operation: CrudOperations,
  ): Promise<TransactionResponse<M>> {
    try {
      const hook = `after${operation.charAt(0).toUpperCase() + operation.slice(1)}`;
      const handler = this.handlers?.[hook] || undefined;
      Iif (handler && typeof handler === 'function') {
        const result = (await handler.bind(this)(model, repository, this.modelId)) as M | boolean;
        Iif (result === false) {
          return undefined;
        }
        return result as M;
      }
      return model;
    } catch (error: unknown) {
      this.log.for(this).error((error as Error)?.message || String(error));
      return undefined;
    }
  }
 
  /**
   * @description Parses and transforms form data for repository operations.
   * @summary Converts raw form data into the appropriate format for repository operations.
   * For DELETE operations, returns the primary key value (string or number). For CREATE
   * and UPDATE operations, builds a complete model instance using the Model.build method
   * with proper primary key assignment for updates.
   *
   * @param {Partial<Model>} data - The raw form data to be processed
   * @return {Model | string | number} Processed data ready for repository operations
   * @private
   */
  protected buildTransactionModel<M extends Model>(
    data: KeyValue | KeyValue[],
    repository: DecafRepository<M>,
    operation?: OperationKeys,
  ): TransactionResponse<M> {
    Iif (!operation) {
      operation = this.operation as OperationKeys;
    }
    operation = (
      [OperationKeys.READ, OperationKeys.DELETE].includes(operation)
        ? OperationKeys.DELETE
        : operation.toLowerCase()
    ) as OperationKeys;
 
    Iif (Array.isArray(data))
      return data.map((item) => this.buildTransactionModel(item, repository, operation)) as M[];
 
    const pk = Model.pk(repository.class as Constructor<M>) as string;
    const pkType = Metadata.type(repository.class as Constructor<M>, pk as string).name;
    const modelId = (this.modelId || data[pk]) as Primitives;
    Iif (!this.modelId) {
      this.modelId = modelId;
    }
    const uid = this.parsePkValue(operation === OperationKeys.DELETE ? data[pk] : modelId, pkType);
    Iif (operation !== OperationKeys.DELETE) {
      const properties = Metadata.properties(repository.class as Constructor<M>) as string[];
      const relation =
        pk === this.pk
          ? {}
          : properties.includes(this.pk) && !data[this.pk]
            ? { [this.pk]: modelId }
            : {};
      Iif (!String(data?.[pk] || '').trim().length) {
        data[pk] = undefined;
      }
      return Model.build(
        Object.assign(
          data || {},
          relation,
          modelId && !data[this.pk] ? { [this.pk]: modelId } : {},
        ),
        repository.class.name,
      ) as M;
    }
    return uid as PrimaryKeyType;
  }
 
  protected getIndexes(model: M): string[] {
    this.indexes = Object.keys(Model.indexes((model || this.model) as Model) || {});
    return this.indexes;
  }
 
  protected parsePkValue(value: PrimaryKeyType, type: string): PrimaryKeyType {
    return [Primitives.NUMBER, Primitives.BIGINT].includes(type.toLowerCase() as Primitives)
      ? Number(value)
      : value;
  }
 
  protected getModelConstrutor(model: string | Model): Constructor<Model> | undefined {
    return Model.get(typeof model === Primitives.STRING ? String(model) : model?.constructor.name);
  }
 
  protected getModelProperties(clazz: Constructor<M>): (keyof M)[] {
    return Metadata.properties(clazz) as (keyof M)[];
  }
 
  protected getModelPropertyType(constructor: Constructor<M> | string, prop: keyof M): string {
    try {
      return Metadata.type(constructor as Constructor<M>, prop as string)?.name;
    } catch (error: unknown) {
      this.log
        .for(this)
        .info(`${(error as Error)?.message || String(error)}. Tryng get with table Name`);
      constructor = Model.get(
        Model.tableName(this.repository.class as Constructor<M>) as string,
      ) as Constructor<M>;
      return Metadata.type(constructor, prop as string)?.name;
    }
  }
 
  protected getModelPkType(clazz: Constructor<M>): string {
    return this.getModelPropertyType(clazz, Model.pk(clazz) as keyof M);
  }
 
  /**
   * @description Handles repository observation events with debouncing.
   * @summary Processes repository change notifications and routes them appropriately.
   * For CREATE events with a UID, handles them immediately. For other events,
   * passes them to the debounced observer subject to prevent excessive updates.
   *
   * @param {...unknown[]} args - The repository event arguments including table, event type, and UID
   * @returns {Promise<void>}
   */
  async handleRepositoryRefresh(...args: unknown[]): Promise<void> {
    const [modelInstance, event, uid] = args;
    Iif ([OperationKeys.CREATE, OperationKeys.DELETE].includes(event as OperationKeys))
      return this.handleObserveEvent(modelInstance, event, uid as string | number);
    return this.repositoryObserverSubject.next(args);
  }
 
  async handleObserveEvent(...args: unknown[]): Promise<void> {
    this.log.for(this.handleObserveEvent).info(`Repository change observed with args: ${args}`);
  }
}