Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

amocrm-js

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

amocrm-js - npm Package Compare versions

Comparing version 3.1.5 to 3.2.0

dist/api/activeRecords/Contact.d.ts

54

dist/api/activeRecords/Lead.d.ts

@@ -5,10 +5,8 @@ /**

import ResourceEntity from "../ResourceEntity";
import { JSONObject } from "../../types";
import { JSONObject, TConstructor } from "../../types";
import { IRequestOptions } from "../../interfaces/common";
import LeadFactory, { LeadsGetByIdCriteria } from "../factories/LeadFactory";
export default class Lead extends ResourceEntity<LeadFactory> {
/**
* Сделка
* @decorator `@fillable`
*/
import { ILeadFactory } from "../factories/LeadFactory";
import { IEntityAttributes, IResourceEntity } from "../../interfaces/api";
import { IHasGetByIdCriteria } from "../factories/mixins/hasGetById";
export interface LeadAttributes extends IEntityAttributes {
id?: number;

@@ -35,7 +33,5 @@ name?: string;

_embedded?: JSONObject;
}
export interface ILead extends IResourceEntity<ILeadFactory>, LeadAttributes {
/**
* @returns присутствует ли сущность на портале AmoCRM
* */
isNew(): boolean;
/**
* Добавляет сущность на портал AmoCRM

@@ -57,3 +53,3 @@ * @example

* */
create(options?: IRequestOptions): Promise<Lead>;
create(options?: IRequestOptions): Promise<ILead>;
/**

@@ -70,3 +66,3 @@ * Обновляет сущность на портале AmoCRM.

* */
update(options?: IRequestOptions): Promise<Lead>;
update(options?: IRequestOptions): Promise<ILead>;
/**

@@ -76,3 +72,3 @@ * Создаёт или сохраняет сущность, в зависимости от результата {@link isNew()}

* */
save(options?: IRequestOptions): Promise<Lead>;
save(options?: IRequestOptions): Promise<ILead>;
/**

@@ -88,3 +84,31 @@ * Получает содержимое сущности на портале

* */
fetch(criteria?: LeadsGetByIdCriteria, options?: IRequestOptions): Promise<false | Lead | null>;
fetch(criteria?: IHasGetByIdCriteria, options?: IRequestOptions): Promise<ILead>;
}
/**
* Сделка
*/
export declare class BaseLead extends ResourceEntity<ILeadFactory> {
name?: string;
price?: number;
responsible_user_id?: number;
group_id?: number;
status_id?: number;
pipeline_id?: number;
loss_reason_id?: number;
source_id?: number;
created_by?: number;
updated_by?: number;
closed_at?: number;
created_at?: number;
closed_task_at?: number;
is_deleted?: boolean;
custom_fields_values?: JSONObject[] | null;
score?: number | null;
account_id?: number;
is_price_modified_by_robot?: boolean;
_embedded?: JSONObject;
getAttributes(): LeadAttributes;
setAttributes(attributes: LeadAttributes): void;
}
declare const Lead: TConstructor<ILead>;
export default Lead;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseLead = void 0;
const tslib_1 = require("tslib");

@@ -8,171 +9,62 @@ /**

const ResourceEntity_1 = tslib_1.__importDefault(require("../ResourceEntity"));
const fillable_1 = require("./decorators/fillable");
class Lead extends ResourceEntity_1.default {
/**
* @returns присутствует ли сущность на портале AmoCRM
* */
isNew() {
return this.id !== undefined;
const util_1 = require("../../util");
const hasSave_1 = require("./mixins/hasSave");
const hasFetch_1 = require("./mixins/hasFetch");
const hasCreate_1 = require("./mixins/hasCreate");
const hasUpdate_1 = require("./mixins/hasUpdate");
/**
* Сделка
*/
class BaseLead extends ResourceEntity_1.default {
getAttributes() {
return {
id: this.id,
name: this.name,
price: this.price,
responsible_user_id: this.responsible_user_id,
group_id: this.group_id,
status_id: this.status_id,
pipeline_id: this.pipeline_id,
loss_reason_id: this.loss_reason_id,
source_id: this.source_id,
created_by: this.created_by,
updated_at: this.updated_at,
closed_task_at: this.closed_task_at,
is_deleted: this.is_deleted,
custom_fields_values: this.custom_fields_values,
score: this.score,
account_id: this.account_id,
is_price_modified_by_robot: this.is_price_modified_by_robot,
_embedded: this._embedded
};
}
/**
* Добавляет сущность на портал AmoCRM
* @example
* ```ts
* const lead = new client.Lead({
* name: "Walter White"
* });
* await lead.create();
* ```
* @example
* ```ts
* const lead = new client.Lead;
* lead.name = "Walter White";
* await lead.create();
* ```
* @returns ссылка на созданную сущность
* */
create(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const criteria = [this];
const [lead] = yield this.factory.create(criteria, options);
this.emit('create');
return lead;
});
setAttributes(attributes) {
this.id = attributes.id;
this.name = attributes.name;
this.price = attributes.price;
this.responsible_user_id = attributes.responsible_user_id;
this.group_id = attributes.group_id;
this.status_id = attributes.status_id;
this.pipeline_id = attributes.pipeline_id;
this.loss_reason_id = attributes.loss_reason_id;
this.source_id = attributes.source_id;
this.created_by = attributes.created_by;
this.updated_by = attributes.updated_by;
this.closed_task_at = attributes.closed_task_at;
this.is_deleted = attributes.is_deleted;
this.custom_fields_values = attributes.custom_fields_values;
this.score = attributes.score;
this.account_id = attributes.account_id;
this.is_price_modified_by_robot = attributes.is_price_modified_by_robot;
this._embedded = attributes._embedded;
}
/**
* Обновляет сущность на портале AmoCRM.
* @param options настройки запроса и обработки результата
* @example
* ```ts
* const lead = await client.leads.getById(123);
* lead.name = "Walter White";
* await lead.update();
* ```
* @returns ссылка на обновлённую сущность
* */
update(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const criteria = [this];
const [lead] = yield this.factory.update(criteria, options);
this.emit('update');
return lead;
});
}
/**
* Создаёт или сохраняет сущность, в зависимости от результата {@link isNew()}
* @param options настройки запроса и обработки результата
* */
save(options) {
if (this.isNew()) {
return this.create(options);
}
return this.update(options);
}
/**
* Получает содержимое сущности на портале
* @param criteria фильтр для уточнения результатов запроса
* @param options настройки запроса и обработки результата
* @example
* ```ts
* const lead = new client.Lead({ id: 123 });
* await lead.fetch();
* ```
* */
fetch(criteria, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (this.isNew()) {
return false;
}
const id = this.id;
const lead = yield this.factory.getById(id, criteria, options);
this.emit('fetch');
return lead;
});
}
}
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", String)
], Lead.prototype, "name", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "price", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "responsible_user_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "group_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "status_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "pipeline_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "loss_reason_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "source_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "created_by", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "updated_by", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "closed_at", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "created_at", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "updated_at", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "closed_task_at", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Boolean)
], Lead.prototype, "is_deleted", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Object)
], Lead.prototype, "custom_fields_values", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Object)
], Lead.prototype, "score", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Number)
], Lead.prototype, "account_id", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Boolean)
], Lead.prototype, "is_price_modified_by_robot", void 0);
tslib_1.__decorate([
(0, fillable_1.fillable)(),
tslib_1.__metadata("design:type", Object)
], Lead.prototype, "_embedded", void 0);
exports.BaseLead = BaseLead;
const Lead = (0, util_1.applyMixins)(BaseLead, [
hasCreate_1.hasCreate,
hasUpdate_1.hasUpdate,
hasSave_1.hasSave,
hasFetch_1.hasFetch
]);
exports.default = Lead;
//# sourceMappingURL=Lead.js.map

@@ -5,17 +5,9 @@ /**

import ResourceFactory from "../ResourceFactory";
import Lead from "../activeRecords/Lead";
import { ILead } from "../activeRecords/Lead";
import ResourcePagination from "../ResourcePagination";
import { IRequestOptions } from "../../interfaces/common";
import { JSONObject } from "../../types";
export interface LeadsGetCriteria {
with?: string;
page?: number;
limit?: number;
query?: string | number;
filter?: string;
order?: string;
}
export interface LeadsGetByIdCriteria {
with?: string;
}
import { IResourceFactory } from "../../interfaces/api";
import { IGetCriteria } from "./mixins/hasGetByCriteria";
import { IHasGetByIdCriteria } from "./mixins/hasGetById";
export interface LeadsCreateCriteria {

@@ -35,31 +27,6 @@ name?: string;

}
export interface LeadCreateResult {
export interface LeadsUpdateCriteria extends LeadsCreateCriteria {
id: number;
request_id: string;
}
export interface LeadsUpdateCriteria {
id: number;
name?: string;
price?: number;
status_id?: number;
pipeline_id?: number;
created_by?: number;
closed_at?: number;
created_at?: number;
updated_at?: number;
loss_reason_id?: number;
responsible_user_id?: number;
custom_fields_values?: JSONObject[];
request_id?: string;
}
export interface LeadUpdateResult {
id: number;
request_id: string;
updated_at: number;
}
/**
* Основной класс фабрики
* */
export default class LeadFactory extends ResourceFactory<Lead> {
createEntity(): Lead;
export interface ILeadFactory extends IResourceFactory<ILead> {
/**

@@ -92,3 +59,3 @@ * @param criteria фильтр сделок (https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-list)

* */
get(criteria?: LeadsGetCriteria, options?: IRequestOptions): Promise<ResourcePagination<Lead>>;
get(criteria?: IGetCriteria, options?: IRequestOptions): Promise<ResourcePagination<ILead>>;
/**

@@ -107,3 +74,3 @@ * Находит сделку по её id

* */
getById(identity: number, criteria?: LeadsGetByIdCriteria, options?: IRequestOptions): Promise<Lead | null>;
getById(identity: number, criteria?: IHasGetByIdCriteria, options?: IRequestOptions): Promise<ILead | null>;
/**

@@ -162,8 +129,4 @@ * Создаёт новые сделки

* */
create(criteria: (LeadsCreateCriteria | Lead)[], options?: IRequestOptions): Promise<Lead[]>;
create(criteria: (LeadsCreateCriteria | ILead)[], options?: IRequestOptions): Promise<ILead[]>;
/**
* @todo https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-complex-add
* */
complexCreate(): Promise<boolean>;
/**
* Обновляет существующие сделки. Принцип работы метода аналогичен {@link create}

@@ -176,3 +139,17 @@ * @param criteria параметры обновления сделок (https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-edit)

* */
update(criteria: (LeadsUpdateCriteria | Lead)[], options?: IRequestOptions): Promise<Lead[]>;
update(criteria: (LeadsUpdateCriteria | ILead)[], options?: IRequestOptions): Promise<ILead[]>;
}
/**
* Фабрика управления сделками
* */
export declare class BaseLeadFactory extends ResourceFactory<ILead> {
getEntityClass(): import("../../types").TConstructor<ILead>;
getBaseUrl(): string;
getEmbeddedKey(): string;
/**
* @todo https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-complex-add
* */
complexCreate(): Promise<boolean>;
}
declare const LeadFactory: any;
export default LeadFactory;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseLeadFactory = void 0;
const tslib_1 = require("tslib");

@@ -10,151 +11,21 @@ /**

const v4_1 = tslib_1.__importDefault(require("../../schema/v4"));
const ResourcePagination_1 = tslib_1.__importDefault(require("../ResourcePagination"));
const ResourceEntity_1 = tslib_1.__importDefault(require("../ResourceEntity"));
const hasGetByCriteria_1 = require("./mixins/hasGetByCriteria");
const hasGetById_1 = require("./mixins/hasGetById");
const hasCreate_1 = require("./mixins/hasCreate");
const hasUpdate_1 = require("./mixins/hasUpdate");
const util_1 = require("../../util");
/**
* Основной класс фабрики
* Фабрика управления сделками
* */
class LeadFactory extends ResourceFactory_1.default {
createEntity() {
return new Lead_1.default(this);
class BaseLeadFactory extends ResourceFactory_1.default {
getEntityClass() {
return Lead_1.default;
}
/**
* @param criteria фильтр сделок (https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-list)
* @example
* ```ts
* const pagination = await client.leads.get({
* order: 'created_at',
* page: 2,
* query: 'Иванов'
* })
* ```
* @param options настройки запроса и обработки результата
* @returns постраничную навигацию, экземпляр {@link ResourcePagination}
*
* @example
* ```ts
* const pagination = await client.leads.get()
* const data = pagination.getData(); // [lead, lead]
* const page = pagination.getPage();
*
* await pagination.next();
*
* const nextData = pagination.data();
* ```
*
* Метод {@link ResourcePagination.getData | getData()} навигации вернёт массив объектов {@link Lead}
*
* */
get(criteria, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const url = v4_1.default.entities.leads.path;
const params = {
url,
criteria,
options,
factory: this,
embedded: 'leads'
};
const pagination = new ResourcePagination_1.default(this.request, params);
yield pagination.fetch();
this.emit('get');
return pagination;
});
getBaseUrl() {
return v4_1.default.entities.leads.path;
}
/**
* Находит сделку по её id
* @param identity id сделки
* @param criteria параметры получения сделки (https://www.amocrm.ru/developers/content/crm_platform/leads-api#lead-detail)
* @example
* ```ts
* const lead = client.leads.getById(123, {
* with: 'catalog_elements'
* })
* ```
* @param options настройки запроса и обработки результата
* @returns экземпляр найденной сделки или null, если сделка не найдена.
* */
getById(identity, criteria, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const url = v4_1.default.entities.leads.path + '/' + identity;
const { data } = yield this.request.get(url, criteria, options);
if (!data) {
return null;
}
const lead = this.createEntity();
lead.setAttributes(data);
return lead;
});
getEmbeddedKey() {
return 'leads';
}
/**
* Создаёт новые сделки
* @param criteria параметры создания сделок (https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-add)
* и/или массив объектов {@link Lead}
* @example
* ```ts
* const leads = await client.leads.create([
* {
* name: "Lead 1"
* },
* {
* name: "Lead 2"
* }
* ])
* ```
*
* @example
* ```ts
* const lead1 = new client.Lead;
* lead1.name = 'Lead 1';
* const lead2 = new client.Lead;
* lead2.name = 'Lead 2';
*
* await client.leads.create([lead1, lead2])
* ```
*
* @example
* ```ts
* const leads = await client.leads.create([
* new client.Lead({
* name: "Lead 1"
* }),
* {
* name: "Lead 2"
* }
* ]);
* ```
*
* @param options настройки запроса и обработки результата
* @returns массив объектов {@link Lead}. Если в параметр criteria передавались экземпляры {@link Lead}, после
* создания сделок в AmoCRM, у них обновится поле id
*
* @example
* ```ts
* const lead1 = new client.Lead;
* lead1.name = 'Lead 1';
* lead1.id; // undefined;
*
* await client.leads.create([lead1])
*
* lead1.id; // 123
* ```
* */
create(criteria, options) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const url = v4_1.default.entities.leads.path;
const requestCriteria = this.getEntityCriteria(criteria);
const { data } = yield this.request.post(url, requestCriteria, options);
const response = ((_a = data === null || data === void 0 ? void 0 : data._embedded) === null || _a === void 0 ? void 0 : _a.leads) || [];
const result = response.map((attributes, index) => {
const entityCriteria = criteria[index];
const lead = entityCriteria instanceof ResourceEntity_1.default ?
entityCriteria :
this.from(entityCriteria);
lead.id = attributes.id;
return lead;
});
return result;
});
}
/**
* @todo https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-complex-add

@@ -167,31 +38,11 @@ * */

}
/**
* Обновляет существующие сделки. Принцип работы метода аналогичен {@link create}
* @param criteria параметры обновления сделок (https://www.amocrm.ru/developers/content/crm_platform/leads-api#leads-edit)
* и/или массив объектов {@link Lead}
* @param options настройки запроса и обработки результата
* @returns массив объектов {@link Lead}. Если в параметр criteria передавались экземпляры {@link Lead}, после
* создания сделок в AmoCRM, у них обновится поле id
* */
update(criteria, options) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const url = v4_1.default.entities.leads.path;
const requestCriteria = this.getEntityCriteria(criteria);
const { data } = yield this.request.patch(url, requestCriteria, options);
const response = ((_a = data === null || data === void 0 ? void 0 : data._embedded) === null || _a === void 0 ? void 0 : _a.leads) || [];
const result = response.map((attributes, index) => {
const entityCriteria = criteria[index];
const lead = entityCriteria instanceof Lead_1.default ?
entityCriteria :
this.from(entityCriteria);
lead.id = attributes.id;
lead.updated_at = attributes.updated_at;
return lead;
});
return result;
});
}
}
exports.BaseLeadFactory = BaseLeadFactory;
const LeadFactory = (0, util_1.applyMixins)(BaseLeadFactory, [
hasGetByCriteria_1.hasGetByCriteria,
hasGetById_1.hasGetById,
hasCreate_1.hasCreate,
hasUpdate_1.hasUpdate
]);
exports.default = LeadFactory;
//# sourceMappingURL=LeadFactory.js.map

@@ -1,3 +0,2 @@

import { JSONObject } from "../types";
import { IResourceEntity } from "../interfaces/api";
import { IEntityAttributes, IResourceEntity, IResourceFactory } from "../interfaces/api";
import EventEmitter from "../common/EventEmitter";

@@ -7,15 +6,21 @@ /**

* */
export default class ResourceEntity<T> extends EventEmitter implements IResourceEntity {
[index: string]: any;
export default abstract class ResourceEntity<T extends IResourceFactory<IResourceEntity<T>>> extends EventEmitter implements IResourceEntity<T> {
id?: number;
updated_at?: number;
protected readonly factory: T;
required: string[];
constructor(factory: T);
getFactory(): T;
/**
* @returns присутствует ли сущность на портале AmoCRM
* */
isNew(): boolean;
/**
* Возвращает все атрибуты сущности, которые должны синхронизироваться с порталом AmoCRM
* */
getAttributes(): JSONObject;
abstract getAttributes(): IEntityAttributes;
/**
* Устанавливает атрибуты сущности, которые должны синхронизироваться с порталом AmoCRM
* */
setAttributes(attributes?: JSONObject): void;
abstract setAttributes(attributes?: IEntityAttributes): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fillable_1 = require("./activeRecords/decorators/fillable");
const EventEmitter_1 = tslib_1.__importDefault(require("../common/EventEmitter"));

@@ -15,26 +14,10 @@ /**

}
/**
* Возвращает все атрибуты сущности, которые должны синхронизироваться с порталом AmoCRM
* */
getAttributes() {
return (0, fillable_1.getFillable)(this)
.reduce((target, key) => {
if (key in this) {
target[key] = this[key];
}
return target;
}, {});
getFactory() {
return this.factory;
}
/**
* Устанавливает атрибуты сущности, которые должны синхронизироваться с порталом AmoCRM
* @returns присутствует ли сущность на портале AmoCRM
* */
setAttributes(attributes) {
if (!attributes) {
return;
}
for (const attr in attributes) {
if ((0, fillable_1.isFillable)(this, attr)) {
this[attr] = attributes[attr];
}
}
isNew() {
return this.id !== undefined;
}

@@ -41,0 +24,0 @@ }

@@ -1,6 +0,5 @@

import { IResourceFactory } from "../interfaces/api";
import ClientRequest from "../common/ClientRequest";
import { JSONObject } from "../types";
import ResourceEntity from "./ResourceEntity";
import { ICollectionResponse, IEntityAttributes, IResourceEntity, IResourceFactory } from "../interfaces/api";
import { IClientRequest } from "../common/ClientRequest";
import EventEmitter from "../common/EventEmitter";
import { TConstructor } from "../types";
/**

@@ -10,14 +9,26 @@ * Основной класс фабрики сущностей. Класс-фабрика служит для создания

* */
export default abstract class ResourceFactory<T extends ResourceEntity<ResourceFactory<T>>> extends EventEmitter implements IResourceFactory<T> {
protected readonly request: ClientRequest;
constructor(request: ClientRequest);
export default abstract class ResourceFactory<T extends IResourceEntity<IResourceFactory<T>>> extends EventEmitter implements IResourceFactory<T> {
protected readonly request: IClientRequest;
constructor(request: IClientRequest);
abstract getBaseUrl(): string;
abstract getEmbeddedKey(): string;
getEmbedded<A extends IEntityAttributes>(data: ICollectionResponse<A>): A[];
/**
* @returns новый экземпляр сущности. Например, {@link LeadFactory} вернёт {@link Lead}
* */
abstract createEntity(): T;
createEntity(): T;
abstract getEntityClass(): TConstructor<T>;
/**
* Возвращает ссылку на объект запроса
* */
getRequest(): IClientRequest;
/**
* Форматирует адрес на основе baseUrl фабрики
* */
getUrl(path?: string): string;
/**
* Создаёт сущность и заполняет её атрибутами, которые
* будут синхронизироваться с порталом AmoCRM
* */
from(attributes?: JSONObject): T;
from(attributes?: object): T;
/**

@@ -29,3 +40,3 @@ * Приводит все переданные объекты-сущности в массиве

* */
protected getEntityCriteria<T extends ResourceEntity<ResourceFactory<T>>>(criteriaData: (JSONObject | T)[]): JSONObject[];
getEntityCriteria(criteriaData: (object)[]): IEntityAttributes[];
}

@@ -15,3 +15,27 @@ "use strict";

}
getEmbedded(data) {
const key = this.getEmbeddedKey();
const { _embedded = {} } = data;
return _embedded[key] || [];
}
/**
* @returns новый экземпляр сущности. Например, {@link LeadFactory} вернёт {@link Lead}
* */
createEntity() {
const className = this.getEntityClass();
return new className(this);
}
/**
* Возвращает ссылку на объект запроса
* */
getRequest() {
return this.request;
}
/**
* Форматирует адрес на основе baseUrl фабрики
* */
getUrl(path = '') {
return this.getBaseUrl() + path;
}
/**
* Создаёт сущность и заполняет её атрибутами, которые

@@ -18,0 +42,0 @@ * будут синхронизироваться с порталом AmoCRM

@@ -1,8 +0,8 @@

import ClientRequest from "../common/ClientRequest";
import { IPaginatedResponse, IPaginationLinks, IResourcePagination, IResourcePaginationParams } from "../interfaces/api";
import { IClientRequest } from "../common/ClientRequest";
import { IPaginatedResponse, IPaginationLinks, IResourceEntity, IResourceFactory, IResourcePagination, IResourcePaginationParams } from "../interfaces/api";
/**
* Постраничная навигация вывода сущностей
* */
export default class ResourcePagination<T> implements IResourcePagination<T> {
protected readonly request: ClientRequest;
export default class ResourcePagination<T extends IResourceEntity<IResourceFactory<T>>> implements IResourcePagination<T> {
protected readonly request: IClientRequest;
protected readonly params: IResourcePaginationParams<T>;

@@ -12,3 +12,3 @@ protected data: T[];

protected page: number;
constructor(request: ClientRequest, params: IResourcePaginationParams<T>);
constructor(request: IClientRequest, params: IResourcePaginationParams<T>);
/**

@@ -15,0 +15,0 @@ * Загружает данные первой страницы

@@ -40,3 +40,3 @@ "use strict";

const apiResponse = yield this.request.get(url, criteria, options);
const data = apiResponse.data;
const { data } = apiResponse;
this.page = (data === null || data === void 0 ? void 0 : data._page) || 1;

@@ -43,0 +43,0 @@ this.parseData(data);

import "reflect-metadata";
import { IClientOptions } from "./interfaces/common";
import EventEmitter from "./common/EventEmitter";
import Connection from './common/Connection';
import Environment from "./common/Environment";
import ClientRequest from "./common/ClientRequest";
import Auth from "./common/Auth";
import Token from "./common/Token";
import LeadFactory from "./api/factories/LeadFactory";
import Lead from "./api/activeRecords/Lead";
import { IEntityConstructor, IResourceFactory } from "./interfaces/api";
import { IConnection } from './common/Connection';
import { IEnvironment } from "./common/Environment";
import { IClientRequest } from "./common/ClientRequest";
import { IAuth } from "./common/Auth";
import { IToken } from "./common/Token";
import { ILeadFactory } from "./api/factories/LeadFactory";
import { ILead } from "./api/activeRecords/Lead";
import { JSONObject } from "./types";
import { IResourceEntity, IResourceFactory } from "./interfaces/api";
import { IContact } from "./api/activeRecords/Contact";
import { IContactFactory } from "./api/factories/ContactFactory";
export declare type IClientEntity<T> = (attributes?: JSONObject) => T;
/**

@@ -16,9 +20,11 @@ * Основной класс библиотеки

export default class Client extends EventEmitter {
readonly token: Token;
readonly environment: Environment;
readonly request: ClientRequest;
readonly connection: Connection;
readonly auth: Auth;
readonly Lead: IEntityConstructor<Lead>;
readonly leads: LeadFactory;
readonly token: IToken;
readonly environment: IEnvironment;
readonly request: IClientRequest;
readonly connection: IConnection;
readonly auth: IAuth;
readonly Lead: IClientEntity<ILead>;
readonly Contact: IClientEntity<IContact>;
readonly leads: ILeadFactory;
readonly contacts: IContactFactory;
constructor(options: IClientOptions);

@@ -30,3 +36,3 @@ /**

* */
protected assignEntity<T>(factory: IResourceFactory<T>): IEntityConstructor<T>;
protected assignEntity<T extends IResourceEntity<IResourceFactory<T>>>(factory: IResourceFactory<T>): IClientEntity<T>;
}

@@ -12,2 +12,3 @@ "use strict";

const LeadFactory_1 = tslib_1.__importDefault(require("./api/factories/LeadFactory"));
const ContactFactory_1 = tslib_1.__importDefault(require("./api/factories/ContactFactory"));
/**

@@ -29,2 +30,4 @@ * Основной класс библиотеки

this.Lead = this.assignEntity(this.leads);
this.contacts = new ContactFactory_1.default(this.request);
this.Contact = this.assignEntity(this.contacts);
}

@@ -31,0 +34,0 @@ /**

@@ -6,6 +6,6 @@ /// <reference types="node" />

* */
export default class APIResponseError extends Error {
readonly apiResponse: object;
export default class APIResponseError<T> extends Error {
readonly apiResponse: T;
readonly response: http.IncomingMessage;
constructor(message: string, apiResponse: object, response: http.IncomingMessage);
constructor(message: string, apiResponse: T, response: http.IncomingMessage);
}
import EventEmitter from "./EventEmitter";
import Environment from "./Environment";
import Token from "./Token";
/**
* Компонент авторизации.
* Доступен как client.auth
* */
export default class Auth extends EventEmitter {
protected readonly environment: Environment;
protected readonly token: Token;
constructor(environment: Environment, token: Token);
import { IEnvironment } from "./Environment";
import { IToken } from "./Token";
export interface IAuth {
/**

@@ -22,3 +15,14 @@ * Устанавливает код авторизации и убирает информацию о текущем токене

* */
getUrl(mode: string): string;
}
/**
* Компонент авторизации.
* Доступен как client.auth
* */
export default class Auth extends EventEmitter implements IAuth {
protected readonly environment: IEnvironment;
protected readonly token: IToken;
constructor(environment: IEnvironment, token: IToken);
setCode(code: string): void;
getUrl(mode?: string): string;
}

@@ -16,5 +16,2 @@ "use strict";

}
/**
* Устанавливает код авторизации и убирает информацию о текущем токене
* */
setCode(code) {

@@ -24,8 +21,2 @@ this.environment.set('auth.code', code);

}
/**
* Возвращает адрес OAuth-авторизации
* cм. https://www.amocrm.ru/developers/content/oauth/step-by-step#%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D0%B5-Authorization-code
*
* @param mode popup или post_messageю
* */
getUrl(mode = 'popup') {

@@ -32,0 +23,0 @@ const baseUrl = 'https://www.amocrm.ru/oauth';

@@ -1,4 +0,10 @@

import { IRequestOptions } from "../interfaces/common";
import Connection from "./Connection";
import { IAPIResponse, IRequestOptions } from "../interfaces/common";
import { IConnection } from "./Connection";
import EventEmitter from "./EventEmitter";
export interface IClientRequest {
make<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
get<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
post<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
patch<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
}
/**

@@ -8,9 +14,9 @@ * Компонент запросов к серверу.

* */
export default class ClientRequest extends EventEmitter {
protected readonly connection: Connection;
constructor(connection: Connection);
make<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<import("../interfaces/common").IAPIResponse<T>>;
get<T>(url: string, data?: object, options?: IRequestOptions): Promise<import("../interfaces/common").IAPIResponse<T>>;
post<T>(url: string, data?: object, options?: IRequestOptions): Promise<import("../interfaces/common").IAPIResponse<T>>;
patch<T>(url: string, data?: object, options?: IRequestOptions): Promise<import("../interfaces/common").IAPIResponse<T>>;
export default class ClientRequest extends EventEmitter implements IClientRequest {
protected readonly connection: IConnection;
constructor(connection: IConnection);
make<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
get<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
post<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
patch<T>(url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
}
import EventEmitter from "./EventEmitter";
import { IRequestOptions } from "../interfaces/common";
import Token from "./Token";
import Environment from "./Environment";
import { IAPIResponse, IRequestOptions } from "../interfaces/common";
import { IToken } from "./Token";
import { IEnvironment } from "./Environment";
import AuthServer from "./AuthServer";
import Auth from "./Auth";
import { IAuth } from "./Auth";
export interface IConnection {
update(): Promise<boolean>;
isTokenExpired(): boolean;
connect(): Promise<boolean>;
makeRequest<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
}
/**

@@ -11,9 +17,9 @@ * Компонент управления соединением с порталом

* */
export default class Connection extends EventEmitter {
protected readonly token: Token;
protected readonly environment: Environment;
protected readonly auth: Auth;
export default class Connection extends EventEmitter implements IConnection {
protected readonly token: IToken;
protected readonly environment: IEnvironment;
protected readonly auth: IAuth;
protected connected: boolean;
protected authServer: AuthServer | null;
constructor(environment: Environment, token: Token, auth: Auth);
constructor(environment: IEnvironment, token: IToken, auth: IAuth);
/**

@@ -43,3 +49,3 @@ * При отсуствии OAuth-токена пытается его получить

* */
makeRequest<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<import("../interfaces/common").IAPIResponse<T>>;
makeRequest<T>(method: string, url: string, data?: object, options?: IRequestOptions): Promise<IAPIResponse<T>>;
}
import * as http from 'http';
import { IAPIResponse, DomainRequestOptions } from "../interfaces/common";
import { IAPIResponse, IDomainRequestOptions } from "../interfaces/common";
import { TStringValueObject } from "../types";

@@ -8,6 +8,6 @@ import EventEmitter from "./EventEmitter";

* */
export default class DomainRequest extends EventEmitter {
protected readonly config: DomainRequestOptions;
export default class DomainRequest<T> extends EventEmitter {
protected readonly config: IDomainRequestOptions;
protected readonly hostname: string;
constructor(config: DomainRequestOptions);
constructor(config: IDomainRequestOptions);
protected isFormData(): boolean;

@@ -20,4 +20,4 @@ protected getHeaders(): TStringValueObject;

protected getHostname(): string;
process<T>(): Promise<IAPIResponse<T>>;
protected parseResponse<T>(apiResponse: IAPIResponse<string>): IAPIResponse<T>;
process(): Promise<IAPIResponse<T>>;
protected parseResponse(apiResponse: IAPIResponse<string>): IAPIResponse<T>;
protected makeRequest(): Promise<IAPIResponse<string>>;

@@ -24,0 +24,0 @@ protected onResponse(callback: CallableFunction): (response: http.IncomingMessage) => void;

@@ -8,3 +8,3 @@ "use strict";

const EventEmitter_1 = tslib_1.__importDefault(require("./EventEmitter"));
const JSONResponseParser_1 = tslib_1.__importDefault(require("./response/JSONResponseParser"));
const JSONResponseParser_1 = tslib_1.__importDefault(require("./JSONResponseParser"));
/**

@@ -11,0 +11,0 @@ * Класс запросов к порталу AmoCRM

import { IClientOptions } from "../interfaces/common";
/**
* Компонент настроек окружения.
* Доступен как client.environment
* Хранит и меняет настройки:
* - переданные при создании экземпляра {@link Client}
* - изменённые в процессе работы с помощью {@link Environment.set}
* */
declare class Environment {
protected readonly options: IClientOptions;
constructor(options: IClientOptions);
import { JSONValue } from "../types";
export interface IEnvironment {
/**

@@ -44,3 +36,3 @@ * Возвращает настройки приложения

* */
set<T>(path: string, value: T): this;
set(path: string, value: JSONValue): void;
/**

@@ -52,2 +44,16 @@ * Проверяет наличие настройки

}
/**
* Компонент настроек окружения.
* Доступен как client.environment
* Хранит и меняет настройки:
* - переданные при создании экземпляра {@link Client}
* - изменённые в процессе работы с помощью {@link Environment.set}
* */
declare class Environment implements IEnvironment {
protected readonly options: IClientOptions;
constructor(options: IClientOptions);
get<T>(path?: string, defaultValue?: T): T;
set(path: string, value: JSONValue): this;
exists(path: string): boolean;
}
export default Environment;

@@ -14,28 +14,2 @@ "use strict";

}
/**
* Возвращает настройки приложения
* @param path - путь к настройке(ам)
* @example
* ```ts
* client.environment.get()
* ```
* без значения метод вернёт объект текущих настроек
* @example
* ```ts
* client.environment.get('domain')
* ```
* вернёт имя домена портала
* @example
* ```ts
* client.environment.get('auth')
* ```
* вернёт объект настроек авторизации
* @example
* ```ts
* client.environment.get('auth.client_id')
* ```
* вернёт id OAuth-приложения AmoCRM
* @param defaultValue - значение, которое вернётся при отсутствии настройки
* @returns значение настройки. При отсутствии значения вернётся defaultValue
* */
get(path, defaultValue) {

@@ -45,12 +19,17 @@ if (!this.options) {

}
let value = this.options;
if (!path) {
return value;
return this.options;
}
let value = this.options;
const parts = path.split('.');
for (const key of parts) {
if (!value) {
if (typeof value !== 'object') {
return defaultValue;
}
value = value[key];
if (Array.isArray(value)) {
value = value[+key];
}
else {
value = value[key];
}
}

@@ -62,7 +41,2 @@ if (value === undefined) {

}
/**
* Устанавливает новое значение настройки
* @param path - путь к настройке. Аналогичен path в {@link get}
* @param value - новое значение
* */
set(path, value) {

@@ -79,6 +53,20 @@ if (!this.options) {

const key = parts[i];
if (!handler[key]) {
handler[key] = {};
const numericIndex = +key;
if (typeof handler === 'object') {
if (Array.isArray(handler) && !(numericIndex in handler)) {
handler[numericIndex] = {};
}
if (!Array.isArray(handler) && !(key in handler)) {
handler[key] = {};
}
}
handler = handler[key];
else {
throw new Error('INVALID_PATH');
}
if (Array.isArray(handler)) {
handler = handler[numericIndex];
}
else {
handler = handler[key];
}
}

@@ -89,9 +77,14 @@ const lastKey = parts.pop();

}
handler[lastKey] = value;
if (typeof handler !== 'object') {
throw new Error('INVALID_PATH');
}
const lastNumericIndex = +lastKey;
if (Array.isArray(handler)) {
handler[lastNumericIndex] = value;
}
else {
handler[lastKey] = value;
}
return this;
}
/**
* Проверяет наличие настройки
* @param path - путь к настройке. Аналогичен path в {@link get}
* */
exists(path) {

@@ -98,0 +91,0 @@ return this.get(path) !== undefined;

/// <reference types="node" />
import { EventEmitter as EventEmitterBase } from "events";
export interface IEventEmitter extends EventEmitterBase.EventEmitter {
subscribe(subscriber: IEventEmitter): IEventEmitter;
unsubscribe(subscriber: IEventEmitter): IEventEmitter;
}
/**

@@ -7,3 +11,3 @@ * Расширяет функционал работы с событиями в NodeJS.

* */
export default class EventEmitter extends EventEmitterBase {
export default class EventEmitter extends EventEmitterBase implements IEventEmitter {
protected subscribers: EventEmitter[];

@@ -13,11 +17,11 @@ /**

* */
subscribe(subscriber: EventEmitter): void;
subscribe(subscriber: EventEmitter): this;
/**
* Отписка от событий
* */
unsubscribe(subscriber: EventEmitter): void;
unsubscribe(subscriber: EventEmitter): this;
/**
* Формирует событие у целевого объекта и у подписчиков
* */
emit(eventName: string | symbol, ...args: any[]): boolean;
emit(eventName: string | symbol, ...args: unknown[]): boolean;
}

@@ -18,2 +18,3 @@ "use strict";

this.subscribers.push(subscriber);
return this;
}

@@ -25,2 +26,3 @@ /**

this.subscribers = this.subscribers.filter(s => s !== subscriber);
return this;
}

@@ -27,0 +29,0 @@ /**

@@ -5,15 +5,8 @@ /// <reference types="node" />

import { IAPIResponse, IResponseParser } from "../../interfaces/common";
import { JSONObject } from "../../types";
/**
* Преобразует ответ портала в JSON-объект
* */
export default class JSONResponseParser extends EventEmitter implements IResponseParser<string, JSONObject | null> {
parse(apiResponse: IAPIResponse<string>): {
response: http.IncomingMessage;
data: null;
} | {
response: http.IncomingMessage;
data: JSONObject;
};
checkErrors(data: object, response: http.IncomingMessage): void;
export default class JSONResponseParser extends EventEmitter implements IResponseParser<string> {
parse<T>(apiResponse: IAPIResponse<string>): IAPIResponse<T>;
checkErrors<T>(data: T, response: http.IncomingMessage): void;
}

@@ -13,5 +13,6 @@ "use strict";

if (!apiResponse.data) {
const data = {};
return {
response,
data: null
data
};

@@ -18,0 +19,0 @@ }

@@ -6,4 +6,4 @@ import EventEmitter from "../EventEmitter";

* */
export default class RawResponseParser extends EventEmitter implements IResponseParser<string, string> {
export default class RawResponseParser extends EventEmitter implements IResponseParser<string> {
parse(apiResponse: IAPIResponse<string>): IAPIResponse<string>;
}
import EventEmitter from "./EventEmitter";
import { IAPIResponse, ITokenData } from "../interfaces/common";
import Environment from "./Environment";
import { IEnvironment } from "./Environment";
import { TStringValueObject } from "../types";
/**
* Компонент управления текущим oAuth-токеном
* Доступен как client.token
* */
export default class Token extends EventEmitter {
protected value?: ITokenData;
protected expiresAt?: Date;
protected code?: string;
protected readonly environment: Environment;
constructor(environment: Environment);
export interface IToken extends EventEmitter {
/**

@@ -36,2 +27,26 @@ * Проверяет, истёк ли токен

/**
* Получает токен по коду авторизации
* */
fetch(): Promise<ITokenData | undefined>;
/**
* Обновляет токен по значению refresh_token
* */
refresh(): Promise<ITokenData | undefined>;
}
/**
* Компонент управления текущим oAuth-токеном
* Доступен как client.token
* */
export default class Token extends EventEmitter {
protected value?: ITokenData;
protected expiresAt?: Date;
protected code?: string;
protected readonly environment: IEnvironment;
constructor(environment: IEnvironment);
isExpired(): boolean;
clear(): void;
exists(): boolean;
setValue(value: ITokenData): void;
getValue(): ITokenData | undefined;
/**
* Возвращает базовые настройки клиентского приложения AmoCRM: id, secret, redirect_uri

@@ -44,12 +59,6 @@ * */

};
/**
* Получает токен по коду авторизации
* */
fetch(): Promise<ITokenData | undefined>;
/**
* Обновляет токен по значению refresh_token
* */
refresh(): Promise<ITokenData | undefined>;
handleResponse(apiResponse: IAPIResponse<ITokenData>): ITokenData | undefined;
protected handleResponse(apiResponse: IAPIResponse<ITokenData>): ITokenData | undefined;
protected makeRequest(data: TStringValueObject): Promise<IAPIResponse<ITokenData>>;
}

@@ -16,5 +16,2 @@ "use strict";

}
/**
* Проверяет, истёк ли токен
* */
isExpired() {

@@ -28,5 +25,2 @@ this.emit('expirationCheck');

}
/**
* Стирает информацию о текущем токене
* */
clear() {

@@ -36,11 +30,5 @@ this.value = undefined;

}
/**
* Проверяет, существует ли текущий токен
* */
exists() {
return this.value !== undefined;
}
/**
* Устанавливает текущее значение токена
* */
setValue(value) {

@@ -57,5 +45,2 @@ this.emit('beforeChange');

}
/**
* Возвращает текущее значение токена
* */
getValue() {

@@ -79,5 +64,2 @@ return this.value;

}
/**
* Получает токен по коду авторизации
* */
fetch() {

@@ -98,5 +80,2 @@ return tslib_1.__awaiter(this, void 0, void 0, function* () {

}
/**
* Обновляет токен по значению refresh_token
* */
refresh() {

@@ -103,0 +82,0 @@ return tslib_1.__awaiter(this, void 0, void 0, function* () {

import Client from './Client';
import { IClientOptions } from "./interfaces/common";
/**
* Функция обратной совместимости
* */
declare function BackwardCompatibility(options: IClientOptions): Client;
declare namespace BackwardCompatibility {
var Client: typeof import("./Client").default;
}
export { Client };
export default BackwardCompatibility;

@@ -7,17 +7,2 @@ "use strict";

exports.Client = Client_1.default;
/**
* Функция обратной совместимости
* */
function BackwardCompatibility(options) {
console.warn('\x1b[33m%s\x1b[0m', 'ВНИМАНИЕ');
console.warn('Используйте');
console.warn('\x1b[32m%s\x1b[0m', 'const { Client } = require("amocrm-js")');
console.warn('Вместо');
console.warn('\x1b[31m%s\x1b[0m', 'const Client = require("amocrm-js")');
console.warn('\x1b[33m%s\x1b[0m', 'В будущих версиях библиотеки старый способ будет удалён');
return new Client_1.default(options);
}
BackwardCompatibility.Client = Client_1.default;
exports.default = BackwardCompatibility;
module.exports = BackwardCompatibility;
//# sourceMappingURL=index.js.map

@@ -1,14 +0,36 @@

import ClientRequest from "../common/ClientRequest";
import { JSONObject } from "../types";
/// <reference types="node" />
import { IClientRequest } from "../common/ClientRequest";
import { JSONObject, TConstructor } from "../types";
import { IRequestOptions } from "./common";
export interface IResourceFactory<T> {
createEntity(): IResourceEntity;
from(attributes?: JSONObject): T;
import { IEventEmitter } from "../common/EventEmitter";
import EventEmitter from "events";
export interface IResourceFactory<T extends IResourceEntity<IResourceFactory<T>>> extends IEventEmitter {
getEntityClass(): TConstructor<T>;
createEntity(): T;
from(attributes?: IEntityAttributes): T;
getRequest(): IClientRequest;
getEmbeddedKey(): string;
getEmbedded<A extends IEntityAttributes>(data: ICollectionResponse<A>): A[];
getUrl(path?: string): string;
getEntityCriteria(criteriaData: (object)[]): IEntityAttributes[];
}
export interface IResourceEntity {
setAttributes(attributes?: JSONObject): void;
export interface IResourceEntity<T extends IResourceFactory<IResourceEntity<T>>> extends EventEmitter.EventEmitter, IEventEmitter {
id?: number;
updated_at?: number;
isNew(): boolean;
getFactory(): T;
getAttributes(): IEntityAttributes;
setAttributes(attributes?: IEntityAttributes): void;
}
export interface IResourceEntityConstructor<T> {
from(request: ClientRequest, attributes?: JSONObject): T;
from(request: IClientRequest, attributes?: JSONObject): T;
}
export interface ICollectionResponse<T> {
_links: {
href: string;
};
_embedded: {
[index: string]: T[];
};
}
export interface IResourcePagination<T> {

@@ -24,3 +46,3 @@ fetch(): void;

}
export interface IResourcePaginationParams<T> {
export interface IResourcePaginationParams<T extends IResourceEntity<IResourceFactory<T>>> {
url: string;

@@ -43,4 +65,8 @@ criteria?: object;

};
_embedded: JSONObject;
_embedded: {
[index: string]: IEntityAttributes[];
};
}
export declare type IEntityConstructor<T> = (attributes?: JSONObject) => T;
export interface IEntityAttributes {
id?: number;
}

@@ -17,2 +17,3 @@ /// <reference types="node" />

export interface IClientOptions {
[index: string]: string | object;
domain: string;

@@ -31,5 +32,5 @@ auth: IAuthOptions;

useFormData?: boolean;
parser?: IResponseParser<string, any>;
parser?: IResponseParser<string>;
}
export interface DomainRequestOptions {
export interface IDomainRequestOptions {
domain: string;

@@ -62,7 +63,4 @@ method: string;

}
export interface IResponseParser<T, R> {
parse(result: IAPIResponse<T>): IAPIResponse<R>;
export interface IResponseParser<T> {
parse<R>(result: IAPIResponse<T>): IAPIResponse<R>;
}
export interface Class<T> {
new (...args: any[]): T;
}

@@ -9,4 +9,7 @@ declare const _default: {

};
contacts: {
path: string;
};
};
};
export default _default;

@@ -10,2 +10,5 @@ "use strict";

path: '/api/v4/leads'
},
contacts: {
path: '/api/v4/contacts'
}

@@ -12,0 +15,0 @@ }

@@ -1,11 +0,13 @@

import { IAPIResponseErrorValue } from "./interfaces/common";
import { IResourceEntity, IResourceFactory } from "./interfaces/api";
export declare type TStringValueObject = {
[name: string]: string;
[index: string]: string;
};
export declare type TAPIResponseValue = JSONValue | IAPIResponseErrorValue;
export declare type JSONValue = string | number | boolean | {
[x: string]: JSONValue;
} | Array<JSONValue>;
export declare type JSONObject = {
[x: string]: any;
};
export interface JSONObject {
[x: string]: JSONValue;
}
export declare type TConstructor<T> = new (...args: any[]) => T;
export declare type TFactoryConstructor<T extends IResourceEntity<IResourceFactory<T>>> = TConstructor<IResourceFactory<T>>;
export declare type TEntityConstructor<T extends IResourceFactory<IResourceEntity<T>>> = TConstructor<IResourceEntity<T>>;
export declare const delay: (ms: number) => Promise<unknown>;
export declare function applyMixins(baseClass: any, mixins: any[]): any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.delay = void 0;
exports.applyMixins = exports.delay = void 0;
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
exports.delay = delay;
/* eslint-disable @typescript-eslint/no-explicit-any */
function applyMixins(baseClass, mixins) {
return mixins.reduce((target, mixin) => {
return mixin(target);
}, baseClass);
}
exports.applyMixins = applyMixins;
//# sourceMappingURL=util.js.map
{
"name": "amocrm-js",
"version": "3.1.5",
"version": "3.2.0",
"description": "JS Library for AmoCRM",

@@ -5,0 +5,0 @@ "main": "./dist/index.js",

@@ -0,1 +1,2 @@

# AmoCRM

@@ -9,16 +10,2 @@

> :warning: Изменился способ подключения основного класса библиотеки
Было:
```js
const Client = require('amocrm-js');
```
Стало
```js
const { Client } = require('amocrm-js');
```
> :warning: В целях обратной совместимости старый способ работает. В будущих версиях он будет убран
Документация: https://usefulweb.github.io/AmoCRM

@@ -241,2 +228,3 @@

- Сделки [[примеры работы]](./examples/javascript/01-leads)
- Контакты [[примеры работы]](./examples/javascript/02-contacts)

@@ -302,3 +290,3 @@ <a id="requests"></a>

```js
const response = await client.request.patch( '/api/v4/leads', [
const response = await client.request.patch('/api/v4/leads', [
{

@@ -474,17 +462,4 @@ "id": 54886,

Ниже пример реализации через сохранение в файл token.json который лежит рядом со скриптом
[Пример реализации через сохранение в файл](./examples/javascript/00-common/01-session.js)
```js
client.connection.on('change', () => {
const token = client.token.getValue();
fs.writeFileSync('./token.js', JSON.stringify(token));
});
try {
const currentToken = require('./token.js');
client.token.setValue(currentToken);
} catch (e) {
// Файл не найден
}
```
<a id="v2-migration"></a>

@@ -528,2 +503,12 @@ ## Переход с версии 2.x.x

## Примеры
Общее:
- [Сохранение сессии](./examples/javascript/00-common/01-session.js)
- [Работа с сервером авторизации](./examples/javascript/00-oauth/001-get-token-with-server.js)
Работа с фабриками:
- Сделки [[примеры работы]](./examples/javascript/01-leads)
- Контакты [[примеры работы]](./examples/javascript/02-contacts)
## Доска почёта

@@ -530,0 +515,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc