UNPKG

amocrm-client

Version:
57 lines (47 loc) 3 kB
import { ICriteria, IResourceEntityWithEmbedded } from "../../../interfaces/api"; import { TConstructor, TEntityEmbeddedConstructor } from "../../../types"; import { IRequestOptions } from "../../../interfaces/common"; import { ICanGetByIdFactory } from "../../factories/mixins/hasGetById"; import { ResourceCollection } from "../../ResourceCollection"; import { CompanyCriteria } from "../../../interfaces/company"; import { ICompanyFactory, CompanyFactory } from "../../factories/CompanyFactory"; import { Company, ICompany } from "../Company"; interface IEmbeddedWithCompanies { companies: ResourceCollection<ICompany> } export interface IHasCompaniesEntity<T extends ICanGetByIdFactory<IResourceEntityWithEmbedded<T>>> extends IResourceEntityWithEmbedded<T> { companies(criteria?: Pick<ICriteria, "with">, options?: IRequestOptions): Promise<ICompany | false>; } export function hasCompanies<T extends ICanGetByIdFactory<IResourceEntityWithEmbedded<T>>>(Base: TEntityEmbeddedConstructor<T>): TConstructor<IResourceEntityWithEmbedded<T>> { return class HasCompanies extends Base { async comapanies(criteria?: ICriteria<any, any>, options?: IRequestOptions) { let _embedded = this._embedded; if (!this._embedded && !this.id) return false; if (this.id && !this._embedded) { const entity = await (this.getFactory() as T).getById(this.id, { with: "companies" }); if (entity == null) return false; _embedded = entity._embedded; } const embeddedCompanies = (_embedded as IEmbeddedWithCompanies).companies; if (embeddedCompanies.size() === 0) return []; if (Object.keys(embeddedCompanies.first()!).length > 5) return embeddedCompanies; const companyIds: number[][] = new ResourceCollection(embeddedCompanies.pluck("id")).chunk(250).all(); const companies: ResourceCollection<ICompany> = new ResourceCollection<ICompany>([]); const companyFactory: ICompanyFactory = new CompanyFactory(this.getFactory().getRequest()); for (const ids of companyIds) { const mergedCriteria = Object.assign(criteria || {}, { filter: { id: ids }, limit: 250 }) as Partial<CompanyCriteria>; const pagination = await companyFactory.get(mergedCriteria, options); companies.add(pagination.getData().all()); if (!pagination.hasNext() || pagination.getData().size() < 250) continue; let hasNextPage = true; do { const nextPage = await pagination.next(); if (nextPage != false) companies.add(nextPage); else hasNextPage = false; } while (hasNextPage); } (this._embedded as IEmbeddedWithCompanies).companies = companies; return companies; } }; }