UNPKG

amocrm-client

Version:
58 lines (47 loc) 2.93 kB
import { IResourceEntityWithEmbedded } from "../../../interfaces/api"; import { TConstructor, TEntityEmbeddedConstructor } from "../../../types"; import { IRequestOptions } from "../../../interfaces/common"; import { IContact } from "../Contact"; import { ICanGetByIdFactory } from "../../factories/mixins/hasGetById"; import { ResourceCollection } from "../../ResourceCollection"; import { Customer, ICustomer } from "../Customer"; import { CustomerFactory, ICustomerFactory } from "../../factories/CustomerFactory"; import { CustomerCriteria } from "../../../interfaces/customer"; interface IEmbeddedWithCustomers { customers: ResourceCollection<ICustomer> } export interface IHasCustomersEntity<T extends ICanGetByIdFactory<IResourceEntityWithEmbedded<T>>> extends IResourceEntityWithEmbedded<T> { customers(criteria?: Pick<CustomerCriteria, "with">, options?: IRequestOptions): Promise<IContact | false>; } export function hasCustomers<T extends ICanGetByIdFactory<IResourceEntityWithEmbedded<T>>>(Base: TEntityEmbeddedConstructor<T>): TConstructor<IResourceEntityWithEmbedded<T>> { return class HasCompanies extends Base { async customers(criteria?: Pick<CustomerCriteria, "with">, 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 IEmbeddedWithCustomers).customers; if (embeddedCompanies.size() === 0) return []; if (Object.keys(embeddedCompanies.first()!).length > 5) return embeddedCompanies; const customerIds: number[][] = new ResourceCollection(embeddedCompanies.pluck("id")).chunk(250).all(); const customers: ResourceCollection<ICustomer> = new ResourceCollection([]); const companyFactory: ICustomerFactory = new CustomerFactory(this.getFactory().getRequest()); for (const ids of customerIds) { const pagination = await companyFactory.get({ filter: { id: ids }, limit: 250 }, options); customers.add(pagination.getData()); if (!pagination.hasNext() || pagination.getData().size() < 250) continue; let hasNextPage = true; do { const nextPage = await pagination.next(); if (nextPage != false) customers.add(nextPage); else hasNextPage = false; } while (hasNextPage); } (this._embedded as IEmbeddedWithCustomers).customers = customers; return customers; } }; }