Initializes the collection by loading its items from the database.
(
options: InitCollectionOptions<TT, P> = {},
)
| 367 | |
| 368 | /** Initializes the collection by loading its items from the database. */ |
| 369 | async init<TT extends T, P extends string = never>( |
| 370 | options: InitCollectionOptions<TT, P> = {}, |
| 371 | ): Promise<LoadedCollection<Loaded<TT, P>>> { |
| 372 | if (this.#dirty) { |
| 373 | const items = [...this.#items]; |
| 374 | this.#dirty = false; |
| 375 | await this.init(options); |
| 376 | items.forEach(i => this.add(i)); |
| 377 | |
| 378 | return this as unknown as LoadedCollection<Loaded<TT, P>>; |
| 379 | } |
| 380 | |
| 381 | const em = this.getEntityManager()!; |
| 382 | options = { ...options, filters: QueryHelper.mergePropertyFilters(this.property.filters, options.filters)! }; |
| 383 | |
| 384 | if (options.dataloader ?? [DataloaderType.ALL, DataloaderType.COLLECTION].includes(em.config.getDataloaderType())) { |
| 385 | const order = [...this.#items]; // copy order of references |
| 386 | const orderBy = QueryHelper.mergeOrderBy( |
| 387 | options.orderBy, |
| 388 | this.property.orderBy, |
| 389 | this.property.targetMeta?.orderBy, |
| 390 | ); |
| 391 | const customOrder = orderBy.length > 0; |
| 392 | const pivotTable = this.property.kind === ReferenceKind.MANY_TO_MANY && em.getPlatform().usesPivotTable(); |
| 393 | const loader = await em.getDataLoader(pivotTable ? 'm:n' : '1:m'); |
| 394 | const items: TT[] = await loader.load([this, { ...options, orderBy }]); |
| 395 | |
| 396 | if (this.property.kind === ReferenceKind.MANY_TO_MANY) { |
| 397 | this.#initialized = true; |
| 398 | this.#dirty = false; |
| 399 | |
| 400 | if (!customOrder) { |
| 401 | this.reorderItems(items, order); |
| 402 | } |
| 403 | |
| 404 | return this as unknown as LoadedCollection<Loaded<TT, P>>; |
| 405 | } |
| 406 | |
| 407 | this.#items.clear(); |
| 408 | let i = 0; |
| 409 | |
| 410 | for (const item of items) { |
| 411 | this.#items.add(item); |
| 412 | this[i++] = item; |
| 413 | } |
| 414 | |
| 415 | this.#initialized = true; |
| 416 | this.#dirty = false; |
| 417 | |
| 418 | return this as unknown as LoadedCollection<Loaded<TT, P>>; |
| 419 | } |
| 420 | |
| 421 | const populate = Array.isArray(options.populate) |
| 422 | ? options.populate.map(f => (f === '*' ? f : `${this.property.name}.${f}`)) |
| 423 | : [`${this.property.name}${options.ref ? ':ref' : ''}`]; |
| 424 | const schema = this.property.targetMeta!.schema === '*' ? helper(this.owner).__schema : undefined; |
| 425 | await em.populate(this.owner as TT[], populate, { |
| 426 | refresh: true, |
no test coverage detected