### Install moysklad-ts Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Install the moysklad-ts library using npm. This is the first step before initializing the client. ```bash npm install moysklad-ts ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/CONTRIBUTING.md Use this command to install project dependencies. Ensure you have Bun installed and the project cloned. ```bash bun i ``` -------------------------------- ### ApiClient Initialization Example Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Example of creating an ApiClient instance with custom options for authentication, base URL, and batch processing limits. ```typescript const apiClient = new ApiClient({ auth: { token: "abc123" }, baseUrl: "https://api.moysklad.ru/api/remap/1.2", batchGetOptions: { limit: 500, expandLimit: 50, concurrencyLimit: 5 } }); ``` -------------------------------- ### Read Operations Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Examples for fetching data, including listing all items, retrieving a single item by ID, getting the first item matching a filter, and counting the total number of items. ```APIDOC ## Read Operations ### List Items Fetches a list of items with support for pagination and filtering. ```typescript const { rows } = await moysklad.counterparty.list(); ``` ### Get All Items (with auto-pagination) Retrieves all items, automatically handling pagination. ```typescript const { rows } = await moysklad.counterparty.all(); ``` ### Get Item by ID Retrieves a single item by its unique identifier. ```typescript const item = await moysklad.counterparty.get("id"); ``` ### Get First Item by Filter Retrieves the first item that matches the specified filter criteria. ```typescript const { rows } = await moysklad.counterparty.first({ filter: {...} }); ``` ### Get Item Count Retrieves the total count of items. ```typescript const { meta } = await moysklad.counterparty.size(); ``` ``` -------------------------------- ### Basic Authentication Example Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Example of initializing the Moysklad client using Basic authentication with user login and password. ```typescript const moysklad = createMoysklad({ auth: { login: "user@example.com", password: "password123" } }); ``` -------------------------------- ### Token Authentication Example Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Example of initializing the Moysklad client using token authentication. Ensure the token is valid. ```typescript const moysklad = createMoysklad({ auth: { token: "123456789abc" } }); ``` -------------------------------- ### Example: Fetching First 10 Counterparties Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Demonstrates how to fetch the first 10 counterparties using the pagination options. ```typescript // Первые 10 контрагентов const { rows } = await moysklad.counterparty.list({ pagination: { limit: 10, offset: 0 } }); ``` -------------------------------- ### Create Operation Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Example for creating a new entity. ```APIDOC ## Create Operation ### Create Entity Creates a new entity with the provided data. ```typescript const created = await moysklad.counterparty.create({ name: "ООО Ромашка" }); ``` ``` -------------------------------- ### Example: Fetching Second Page of Counterparties Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Shows how to fetch the second page of counterparty data by setting the offset. ```typescript // Вторая страница (позиции 10-19) const { rows } = await moysklad.counterparty.list({ pagination: { limit: 10, offset: 10 } }); ``` -------------------------------- ### Get Demand With Expand Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Example of retrieving a demand document with the agent entity expanded. The agent field will contain the full counterparty object. ```typescript // Когда expand используется const demand = await moysklad.demand.get("123", { expand: { agent: true } }); console.log(demand.agent); // { // id: "...", // name: "ООО Ромашка", // meta: { ... }, // ... // } ``` -------------------------------- ### Create with Full Information Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Provides an example of creating a new entity (e.g., demand) with all necessary details and expanded related objects. ```APIDOC ## Create with Full Information ### Description Creates a new entity with detailed information and expands related entities in the response. ### Method POST (implied by `create` method) ### Endpoint `/entity` (example for demand) ### Parameters #### Request Body - **agent** (object) - Required - Information about the agent. - **meta** (object) - Required - Metadata for the agent. - **href** (string) - Required - URL of the agent. - **type** (string) - Required - Type of the entity (e.g., `Entity.Counterparty`). - **mediaType** (string) - Required - Media type (e.g., `MediaType.Json`). - **organization** (object) - Required - Information about the organization. - **meta** (object) - Required - Metadata for the organization. - **href** (string) - Required - URL of the organization. - **type** (string) - Required - Type of the entity (e.g., `Entity.Organization`). - **mediaType** (string) - Required - Media type (e.g., `MediaType.Json`). - **moment** (string) - Required - The date and time of the entity creation. - **applicable** (boolean) - Required - Whether the entity is applicable. #### Query Parameters - **expand** (object) - Optional - Specifies related entities to expand in the response. - **agent** (boolean) - Optional - Expand agent information. - **organization** (boolean) - Optional - Expand organization information. ### Request Example ```typescript const demand = await moysklad.demand.create({ agent: { meta: { href: "...", type: Entity.Counterparty, mediaType: MediaType.Json } }, organization: { meta: { href: "...", type: Entity.Organization, mediaType: MediaType.Json } }, moment: composeDateTime(new Date()), applicable: true }, { expand: { agent: true, organization: true } }); ``` ### Response #### Success Response (200) - Returns the created entity with expanded related data. ``` -------------------------------- ### get() Method Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Performs an HTTP GET request to a specified URL. ```APIDOC ## get() ### Description Performs a GET request. ### Signature ```typescript get( url: string, options?: { searchParameters?: URLSearchParams, headers?: Record } ): Promise ``` ### Parameters #### Path Parameters - **url** (string) - Required - Resource path - **options.searchParameters** (URLSearchParams) - Optional - Query parameters - **options.headers** (Record) - Optional - Additional headers ### Returns Promise ### Request Example ```typescript const response = await client.get("/entity/counterparty", { searchParameters: new URLSearchParams({ limit: "10" }) }); ``` ``` -------------------------------- ### Example: Iterating Through All Counterparties with Pagination Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Provides a pattern for iterating through all counterparty records by calculating the total number of pages and fetching them sequentially. ```typescript // Использование со смещением const { meta } = await moysklad.counterparty.size(); const perPage = 100; const pages = Math.ceil(meta.size / perPage); for (let i = 0; i < pages; i++) { const { rows } = await moysklad.counterparty.list({ pagination: { limit: perPage, offset: i * perPage } }); processRows(rows); } ``` -------------------------------- ### Example Usage of MoyskladError Handling Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/03-errors.md Shows a practical example of catching a MoyskladError, checking its type, and logging specific details like HTTP status, error message, and request/response information. ```typescript import { MoyskladError } from "moysklad-ts"; try { await moysklad.counterparty.delete("non-existent-id"); } catch (error) { if (error instanceof MoyskladError) { console.log(`HTTP ${error.responseInfo.status}: ${error.message}`); console.log(`Request: ${error.requestInfo.method} ${error.requestInfo.url}`); console.log(`Response: ${error.responseInfo.statusText}`); } } ``` -------------------------------- ### Get All Products with Price Information Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Retrieves all products, expanding their buy and sell prices for detailed cost and sale information. ```typescript const { rows } = await moysklad.product.all({ expand: { buyPrice: true, sellPrice: true } }); ``` -------------------------------- ### Example: Maximum Load for Counterparties Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Illustrates fetching the maximum allowed number of items (1000) in a single request. ```typescript // Максимальная загрузка (мин 1 запрос) const { rows } = await moysklad.counterparty.list({ pagination: { limit: 1000, offset: 0 } }); ``` -------------------------------- ### Combined Usage Examples Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Demonstrates advanced usage patterns including data fetching with multiple expands, filtering lists, and chained create/update operations. ```APIDOC ## Combined Usage Examples ### Fetching data with multiple expands ```typescript const demand = await moysklad.demand.get("document-id", { expand: { agent: { owner: { group: true } }, organization: true, positions: true } }); // Now full objects are available console.log(demand.agent.name); console.log(demand.agent.owner.name); console.log(demand.agent.owner.group.name); ``` ### Working with lists and filtering ```typescript // Get all demands for a specific counterparty within a period const { rows } = await moysklad.demand.all({ filter: { agent: { eq: "counterparty-id" }, moment: { gte: composeDateTime("2024-01-01T00:00:00Z"), lte: composeDateTime("2024-12-31T23:59:59Z") }, applicable: { eq: true } }, order: [ { field: "moment", direction: "desc" }, { field: "name", direction: "asc" } ], expand: { agent: true, positions: true } }); console.log(`Found ${rows.length} demands`); ``` ### Chained creation and update ```typescript // Create a new counterparty const counterparty = await moysklad.counterparty.create({ name: "New Company LLC" }); // Then update with additional information const updated = await moysklad.counterparty.update(counterparty.id, { description: "Main supplier", email: "contact@example.com" }); ``` ``` -------------------------------- ### Full Example: Sync MySklad Products to Local Storage Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/11-integration-examples.md This service synchronizes products from MySklad to a local in-memory database. It handles product data extraction, price and stock retrieval, and updates local records. Ensure the MOYSKLAD_TOKEN environment variable is set. ```typescript import { createMoysklad, composeDateTime, parseDateTime, isAssortmentOfType } from "moysklad-ts"; interface LocalProduct { externalId: string; name: string; price: number; stock: number; lastUpdated: Date; } class ProductSyncService { private moysklad = createMoysklad({ auth: { token: process.env.MOYSKLAD_TOKEN! } }); private localDb: Map = new Map(); /** * Синхронизировать товары из МойСклад в локальное хранилище */ async syncProducts(): Promise { console.log("🔄 Начало синхронизации товаров..."); try { // Получить все товары с раскрытием цен и остатков const { rows: assortments } = await this.moysklad.assortment.all({ expand: { buyPrice: true, sellPrice: true } }); let synced = 0; let skipped = 0; for (const item of assortments) { try { // Пропустить если не товар if (!isAssortmentOfType(item, "product")) { skipped++; continue; } const externalId = item.id; // Получить остатки товара const stock = await this.getProductStock(externalId); // Создать локальный объект товара const localProduct: LocalProduct = { externalId, name: item.name, price: this.extractPrice(item), stock: stock, lastUpdated: parseDateTime(item.updated) }; // Сохранить в локальное хранилище this.localDb.set(externalId, localProduct); synced++; if (synced % 100 === 0) { console.log(`✓ Обработано ${synced} товаров...`); } } catch (error) { console.error(`✗ Ошибка при обработке товара ${item.id}:`, error); } } console.log(`✅ Синхронизация завершена: ${synced} товаров обновлено, ${skipped} пропущено`); } catch (error) { console.error("❌ Ошибка синхронизации:", error); throw error; } } private extractPrice(item: any): number { // Получить цену продажи, или цену закупки, или 0 if (item.sellPrice && item.sellPrice.length > 0) { return item.sellPrice[0].value / 100; } if (item.buyPrice && item.buyPrice.length > 0) { return item.buyPrice[0].value / 100; } return 0; } private async getProductStock(productId: string): Promise { try { const { rows } = await this.moysklad.report.stock.all({ groupBy: "product" }); const stockRecord = rows.find(row => row.assortmentId === productId ); return stockRecord?.stock || 0; } catch (error) { console.warn(`Не удалось получить остаток для ${productId}`); return 0; } } getLocalProduct(externalId: string): LocalProduct | undefined { return this.localDb.get(externalId); } getAllLocalProducts(): LocalProduct[] { return Array.from(this.localDb.values()); } } // Использование async function main() { const syncService = new ProductSyncService(); await syncService.syncProducts(); const allProducts = syncService.getAllLocalProducts(); console.log(`Всего товаров в локальном хранилище: ${allProducts.length}`); } main().catch(console.error); ``` -------------------------------- ### Perform First API Requests Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Examples of common API operations: fetching a list of counterparties, retrieving a single counterparty by ID, and creating a new counterparty. ```typescript // Получить список контрагентов const { rows } = await moysklad.counterparty.list(); // Получить одного контрагента const counterparty = await moysklad.counterparty.get("id"); // Создать контрагента const new_cp = await moysklad.counterparty.create({ name: "ООО Ромашка" }); ``` -------------------------------- ### Low-Level API Client: Perform GET Request Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Execute a generic GET request to a specified API path. Supports custom search parameters for filtering and pagination. ```typescript // Произвольный GET запрос const response = await moysklad.client.get("/entity/counterparty", { searchParameters: new URLSearchParams({ limit: "10" }) }); const data = await response.json(); ``` -------------------------------- ### Example: Nested Expansion (Owner and its Group) Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Shows how to perform nested expansion, retrieving the 'owner' object and then expanding its 'group' field. ```typescript // Раскрыть контрагента и его владельца с его отделом const counterparty = await moysklad.counterparty.get("123", { expand: { owner: { group: true // Раскрыть отдел владельца } } }); console.log(counterparty.owner.group); // Group объект ``` -------------------------------- ### Metadata Interface - Example Usage Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Shows how to access the `meta` object after fetching an entity, such as a counterparty. The output displays the structure of the metadata. ```typescript const counterparty = await moysklad.counterparty.get("123"); console.log(counterparty.meta); // { // href: "https://api.moysklad.ru/api/remap/1.2/entity/counterparty/…", // metadataHref: "…", // mediaType: "application/json", // type: "counterparty" // } ``` -------------------------------- ### Example Usage of MoyskladError Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/03-errors.md Demonstrates how to catch `MoyskladError` and access its properties to log detailed error information. ```APIDOC ### Example Usage ```typescript import { MoyskladError } from "moysklad-ts"; try { await moysklad.counterparty.delete("non-existent-id"); } catch (error) { if (error instanceof MoyskladError) { console.log(`HTTP ${error.responseInfo.status}: ${error.message}`); console.log(`Request: ${error.requestInfo.method} ${error.requestInfo.url}`); console.log(`Response: ${error.responseInfo.statusText}`); } } ``` ``` -------------------------------- ### Batch Payment Import with Retry Logic Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/11-integration-examples.md This example shows how to import payments in batches, including finding counterparties by email and creating incoming payments. It also implements retry logic for transient server errors. ```typescript import { createMoysklad, MoyskladError } from "moysklad-ts"; interface ExternalPayment { id: string; amount: number; date: string; description: string; counterpartyEmail: string; } class PaymentImportService { private moysklad = createMoysklad({ auth: { token: process.env.MOYSKLAD_TOKEN! } }); private batchSize = 10; private retryAttempts = 3; /** * Импортировать платежи */ async importPayments(payments: ExternalPayment[]): Promise<{ success: number; failed: number; errors: Array<{ payment: ExternalPayment; error: string }>; }> { console.log(`💰 Начало импорта ${payments.length} платежей...`); let success = 0; let failed = 0; const errors: Array<{ payment: ExternalPayment; error: string }> = []; for (let i = 0; i < payments.length; i += this.batchSize) { const batch = payments.slice(i, i + this.batchSize); const results = await Promise.allSettled( batch.map(payment => this.processPayment(payment)) ); for (let j = 0; j < results.length; j++) { const result = results[j]; const payment = batch[j]; if (result.status === "fulfilled") { success++; } else { failed++; errors.push({ payment, error: result.reason?.message || "Неизвестная ошибка" }); } } console.log(`📊 Обработано ${Math.min(i + this.batchSize, payments.length)}/${payments.length}`); } console.log(`✅ Импорт завершен: ${success} успешно, ${failed} ошибок`); return { success, failed, errors }; } /** * Обработать один платеж с retry логикой */ private async processPayment( payment: ExternalPayment, attempt = 1 ): Promise { try { // Найти контрагента по email const { rows: counterparties } = await this.moysklad.counterparty.list({ filter: { email: { eq: payment.counterpartyEmail } } }); if (counterparties.length === 0) { throw new Error(`Контрагент с email ${payment.counterpartyEmail} не найден`); } const counterparty = counterparties[0]; // Создать входящий платеж await this.moysklad.paymentIn.create({ agent: { meta: counterparty.meta }, moment: payment.date, applicable: true, sum: payment.amount, description: payment.description, externalCode: payment.id }); console.log(`✓ Платеж ${payment.id} успешно импортирован`); } catch (error) { if ( attempt < this.retryAttempts && error instanceof MoyskladError && error.responseInfo.status >= 500 ) { // Повторить при ошибке 5xx await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); return this.processPayment(payment, attempt + 1); } throw error; } } } // Использование async function main() { const importService = new PaymentImportService(); const payments: ExternalPayment[] = [ { id: "pay-001", amount: 10000, date: new Date().toISOString(), description: "Платеж за заказ #123", counterpartyEmail: "client@example.com" }, { id: "pay-002", amount: 5000, date: new Date().toISOString(), description: "Платеж за заказ #124", counterpartyEmail: "client2@example.com" } ]; const result = await importService.importPayments(payments); console.log("Результат импорта:", result); } main().catch(console.error); ``` -------------------------------- ### Example: Expanding Fields in List Responses Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Demonstrates how to use the 'expand' option when fetching lists, such as expanding 'agent', 'organization', and 'positions' for demand objects. ```typescript const { rows } = await moysklad.demand.list({ expand: { agent: true, organization: true, positions: true } }); for (const demand of rows) { console.log(demand.agent.name); // Полный объект контрагента } ``` -------------------------------- ### list() - Get a paginated list of items Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/09-implementation-guide.md Performs a GET request to the endpoint with pagination, expand, filters, order, and search capabilities. It uses `composeSearchParameters()` to build query parameters and parses the JSON response. ```APIDOC ## GET /items ### Description Retrieves a paginated list of items with support for filtering, sorting, searching, and expanding related resources. ### Method GET ### Endpoint /items ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of items to return per page. - **offset** (integer) - Optional - The number of items to skip before starting to collect the result set. - **expand** (string) - Optional - Comma-separated list of fields to expand. - **filter** (string) - Optional - Filter criteria. - **order** (string) - Optional - Sorting order. - **search** (string) - Optional - Search query. ### Response #### Success Response (200) - **items** (array) - A list of items. - **meta** (object) - Metadata about the response, including pagination information. ``` -------------------------------- ### Delete Operations Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Examples for deleting entities, including single and batch deletions. ```APIDOC ## Delete Operations ### Delete Entity by ID Deletes a single entity by its unique identifier. ```typescript await moysklad.counterparty.delete("id"); ``` ### Batch Delete Entities Deletes multiple entities by providing an array of their IDs. ```typescript await moysklad.counterparty.batchDelete(["id1", "id2"]); ``` ``` -------------------------------- ### Get Data with Expansion Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Demonstrates how to retrieve a specific entity (e.g., demand) and expand related entities like agent, organization, and positions. ```APIDOC ## Get Data with Expansion ### Description Retrieves a specific entity with expanded related data. ### Method GET (implied by `get` method) ### Endpoint `/entity/{id}` (example for demand) ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the entity to retrieve. #### Query Parameters - **expand** (object) - Optional - Specifies related entities to expand. - **agent** (boolean) - Optional - Expand agent information. - **organization** (boolean) - Optional - Expand organization information. - **positions** (boolean) - Optional - Expand positions information. ### Request Example ```typescript const result = await moysklad.demand.get("id", { expand: { agent: true, organization: true, positions: true } }); ``` ### Response #### Success Response (200) - Returns the requested entity with expanded related data. ``` -------------------------------- ### Example Usage of MediaType Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Demonstrates how to use the MediaType enum when constructing an entity link, specifying the content type as JSON. ```typescript import { MediaType, Entity } from "moysklad-ts"; const link = { meta: { href: "https://api.moysklad.ru/api/remap/1.2/entity/counterparty/123", type: Entity.Counterparty, mediaType: MediaType.Json } }; ``` -------------------------------- ### all() - Get all items Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/09-implementation-guide.md Uses `ApiClient.batchGet()` for automatic pagination and concurrency management to retrieve all items. It merges results from all pages and uses `expandLimit` if expand options are present. ```APIDOC ## GET /items (all) ### Description Retrieves all items from the API, handling pagination automatically and merging results from multiple requests. ### Method GET ### Endpoint /items ### Parameters #### Query Parameters - **expand** (boolean) - Optional - Whether to expand related resources. - Other parameters supported by `list()` method can also be passed. ``` -------------------------------- ### Example: Multiple Field Expansion Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Illustrates expanding multiple top-level fields ('owner', 'group', 'organization', 'accounts') in a single request. ```typescript const counterparty = await moysklad.counterparty.get("123", { expand: { owner: true, group: true, organization: true, accounts: true } }); ``` -------------------------------- ### Get All Assortment Items with Owner Info Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Retrieves all items from the assortment (products, services, etc.), expanding owner information. ```typescript const { rows } = await moysklad.assortment.all({ expand: { owner: true } }); ``` -------------------------------- ### ListMetadata Interface - Example Usage Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Illustrates how to retrieve and log the `meta` object from a paginated list response, such as a list of counterparties. The output shows pagination details like total size, limit, offset, and navigation URLs. ```typescript const { meta } = await moysklad.counterparty.list({ pagination: { limit: 10, offset: 20 } }); console.log(meta); // { // href: "…", // type: "counterparty", // mediaType: "application/json", // size: 150, // Всего контрагентов // limit: 10, // На этой странице // offset: 20, // Начиная со смещения // nextHref: "...", // Для получения следующих 10 // previousHref: "..." // Для получения предыдущих 10 // } ``` -------------------------------- ### Example: Expanding a Single Field (Owner) Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/05-common-types.md Demonstrates how to expand a single nested field, such as 'owner', to retrieve the full object instead of just its metadata. ```typescript // Получить контрагента с раскрытым владельцем const counterparty = await moysklad.counterparty.get("123", { expand: { owner: true } }); console.log(counterparty.owner); // Теперь это объект Employee, а не Meta ``` -------------------------------- ### Get All with Filter Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Illustrates fetching all records of a certain type (e.g., counterparty) that match a specific filter and include expanded data. ```APIDOC ## Get All with Filter ### Description Retrieves all entities matching a filter, with options for expansion. ### Method GET (implied by `all` method) ### Endpoint `/entity` (example for counterparty) ### Parameters #### Query Parameters - **filter** (object) - Optional - Criteria to filter the results. - **name** (object) - Optional - Filter by name. - **sw** (string) - Required - Filter by names starting with the given string. - **expand** (object) - Optional - Specifies related entities to expand. - **owner** (boolean) - Optional - Expand owner information. ### Request Example ```typescript const { rows } = await moysklad.counterparty.all({ filter: { name: { sw: "ООО" } }, expand: { owner: true } }); ``` ### Response #### Success Response (200) - **rows** (array) - A list of all entities matching the filter and expansion criteria. ``` -------------------------------- ### Configure Batch Get Options in TypeScript Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/README.md Customize the options for the `.all()` method, which controls batch fetching of entities. Adjust limits for requests with and without `expand`, and set the concurrency limit. ```typescript const moysklad = new Moysklad({ batchGetOptions: { limit: 500, expandLimit: 50, concurrencyLimit: 5 } }); ``` -------------------------------- ### Get All Counterparties in TypeScript Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/README.md Use the `.all()` method on the `counterparty` endpoint to retrieve all counterparties. Ensure the Moysklad class is properly initialized. ```typescript const counterparties = await moysklad.counterparty.all(); ``` -------------------------------- ### Get Demand Without Expand Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Example of retrieving a demand document without expanding related entities. The agent field will only contain metadata. ```typescript // Когда expand не используется const demand = await moysklad.demand.get("123"); console.log(demand.agent); // { // meta: { // href: "...", // type: "counterparty", // ... // } // } ``` -------------------------------- ### get() - Get a single entity Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/09-implementation-guide.md Performs a GET request to the endpoint with a specific ID to retrieve a single entity. Supports expand options for related resources. ```APIDOC ## GET /items/{id} ### Description Retrieves a single entity by its ID, with support for expanding related resources. ### Method GET ### Endpoint /items/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the entity to retrieve. #### Query Parameters - **expand** (string) - Optional - Comma-separated list of fields to expand. ``` -------------------------------- ### Get Counterparty Count Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Retrieve the total count of counterparties. Use this to get the size of the dataset. ```typescript const { meta } = await moysklad.counterparty.size(); ``` -------------------------------- ### Initialization Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Initialize the Moysklad client with either a token or Basic Auth credentials. ```APIDOC ## Initialization ### Description Initialize the Moysklad client with either a token or Basic Auth credentials. ### Code Example ```typescript import { createMoysklad } from "moysklad-ts"; // С токеном const moysklad = createMoysklad({ auth: { token: "your-token" } }); // С Basic Auth const moysklad = createMoysklad({ auth: { login: "email@example.com", password: "password" } }); ``` ``` -------------------------------- ### Perform GET Request Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Convenience method for performing a GET request to a resource. Supports query parameters and custom headers. ```typescript const response = await client.get("/entity/counterparty", { searchParameters: new URLSearchParams({ limit: "10" }) }); ``` -------------------------------- ### Get Single Entity by ID Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/02-main-factory.md Use `get()` to retrieve a single entity by its unique ID. This is the most direct way to fetch a specific record. ```typescript get>( id: string, options?: Subset ): Promise ``` ```typescript const counterparty = await moysklad.counterparty.get("5427bc76-b95f-11eb-0a80-04bb000cd583"); ``` -------------------------------- ### Get Single Entity by ID Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/09-implementation-guide.md Executes a GET request to an endpoint using a specific entity ID. Supports expand options for retrieving related data. ```typescript if (method === "get") { const id = callbackOptions.args[0] as string const options = callbackOptions.args[1] as ComposeSearchParametersOptions | undefined return client .get(`${path}/${id}`, { searchParameters: composeSearchParameters(options ?? {}), }) .then((response) => response.json()) } ``` -------------------------------- ### Creating an Object with Metadata Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Demonstrates how to create a new entity (e.g., a demand) by providing necessary metadata for related objects like agent and organization. ```APIDOC ## Creating an Object with Metadata ### Description Example of creating an entity that requires metadata for its related fields. ### Code Example ```typescript import { Entity, MediaType } from "moysklad-ts"; // API requires meta-information for related objects const demand = await moysklad.demand.create({ agent: { meta: { href: "https://api.moysklad.ru/api/remap/1.2/entity/counterparty/abc-123", type: Entity.Counterparty, mediaType: MediaType.Json } }, organization: { meta: { href: "https://api.moysklad.ru/api/remap/1.2/entity/organization/def-456", type: Entity.Organization, mediaType: MediaType.Json } } }); ``` ``` -------------------------------- ### Get Count of Entities Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/02-main-factory.md Use `size()` to get the total number of entities that match the specified options. The result includes metadata, with the count typically found in `meta.size`. ```typescript size(options?: SizeOptions): Promise> ``` ```typescript const { meta } = await moysklad.counterparty.size(); console.log(`Всего контрагентов: ${meta.size}`); ``` -------------------------------- ### Get First Entity from Filtered List Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/02-main-factory.md Use `first()` to retrieve only the first entity that matches the provided filter options. Useful for quickly checking existence or getting a sample record. ```typescript first>( options?: Subset ): Promise> ``` ```typescript const { rows: [firstCounterparty] } = await moysklad.counterparty.first({ filter: { name: { sw: "ООО" } } }); ``` -------------------------------- ### ApiClient Constructor Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Initializes a new instance of the API client with provided options. ```APIDOC ## constructor ApiClient ### Description Creates a new instance of the API client. ### Signature ```typescript constructor(options: ApiClientOptions) ``` ### Parameters #### Path Parameters - **options** (ApiClientOptions) - Required - Initialization options ### Request Example ```typescript const client = new ApiClient({ auth: { token: "123456" } }); ``` ``` -------------------------------- ### Create a New Product Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Creates a new product with a specified name and article number. ```typescript const product = await moysklad.product.create({ name: "Новый товар", article: "ART-001" }); ``` -------------------------------- ### Get Data with Expansion Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Use the `get` method to retrieve a single entity by its ID and expand related entities to include their data in the response. This is useful when you need detailed information about an entity and its associated objects in one request. ```typescript const result = await moysklad.demand.get("id", { expand: { agent: true, organization: true, positions: true } }); ``` -------------------------------- ### ApiClient Initialization Options Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/01-api-client.md Configuration options for initializing the API client, including authentication, base URL, user agent, and batch processing settings. ```APIDOC ## ApiClientOptions ### Description Options for initializing the API client. ### Parameters #### Request Body - **auth** (Auth) - Required - Authorization options - **baseUrl** (string) - Optional - Base URL for the MоySklad API. Defaults to "https://api.moysklad.ru/api/remap/1.2". - **userAgent** (string) - Optional - User-Agent string for requests. Defaults to "moysklad-ts/{version} (+https://github.com/MonsterDeveloper/moysklad-ts)". - **batchGetOptions** (BatchGetOptions) - Optional - Options for batch data processing. Defaults to `{ limit: 1000, expandLimit: 100, concurrencyLimit: 3 }`. ### Request Example ```typescript const apiClient = new ApiClient({ auth: { token: "abc123" }, baseUrl: "https://api.moysklad.ru/api/remap/1.2", batchGetOptions: { limit: 500, expandLimit: 50, concurrencyLimit: 5 } }); ``` ``` -------------------------------- ### Get Size Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Retrieve the total count of entities. ```APIDOC ## Get Size ### Description Retrieve the total count of entities. ### Code Example ```typescript const { meta } = await moysklad.counterparty.size(); console.log(meta.size); // Общее количество ``` ``` -------------------------------- ### get() Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/02-main-factory.md Retrieves a single entity by its unique ID. ```APIDOC ## get() ### Description Get a single entity by ID. ### Method Signature ```typescript get>( id: string, options?: Subset ): Promise ``` ### Example ```typescript const counterparty = await moysklad.counterparty.get("5427bc76-b95f-11eb-0a80-04bb000cd583"); ``` ``` -------------------------------- ### Initialization Options Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/README.md When initializing the Moysklad client, you can provide various options to configure authentication, base URL, user agent, and batch request limits. ```APIDOC ## Initialization Options ### Description Configure the `Moysklad` client during initialization with various options to customize its behavior, including authentication and API request settings. ### Options | Parameter | Default | Description | |--------------------|-------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `auth` | — | Authentication method. Can be `{ token: string }` for token-based authentication or `{ login: string, password: string }` for HTTP Basic Auth. (See [Moysklad Docs](https://github.com/wmakeev/moysklad#%D0%B0%D1%83%D1%82%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F)) | `baseUrl` | `"https://api.moysklad.ru/api/remap/1.2"` | The base URL for the MoySklad API. | | `userAgent` | `moysklad-ts/${version} (+https://github.com/MonsterDeveloper/moysklad-ts)`, where `{version}` is the library version | The content of the "User-Agent" header sent with requests. Useful for tracking API changes in the "Audit" tab. | | `batchGetOptions` | `{ limit: 1000, expandLimit: 100, concurrencyLimit: 3 }` | Options for fetching all entities from the API (using the `.all()` method). Sets limits for requests with and without `expand`, and for concurrent requests. ``` -------------------------------- ### Update Operation Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Example for updating an existing entity by its ID. ```APIDOC ## Update Operation ### Update Entity Updates an existing entity identified by its ID with new data. ```typescript await moysklad.counterparty.update("id", { name: "ООО Новое имя" }); ``` ``` -------------------------------- ### Get First Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Retrieve the first entity that matches the specified filter criteria. ```APIDOC ## Get First ### Description Retrieve the first entity that matches the specified filter criteria. ### Code Example ```typescript const { rows } = await moysklad.counterparty.first({ filter: { name: { sw: "ООО" } } }); ``` ``` -------------------------------- ### Get Counterparty Count Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Retrieves the total number of counterparties available in the system. ```typescript const { meta } = await moysklad.counterparty.size(); console.log(meta.size); ``` -------------------------------- ### Initialize MoySklad Client Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Configure the MoySklad client with authentication token and optional base URL, user agent, and batch request options. Ensure the token is valid for authentication. ```typescript const moysklad = createMoysklad({ auth: { token: "token" }, baseUrl: "https://api.moysklad.ru/api/remap/1.2", // опционально userAgent: "MyApp/1.0", // опционально batchGetOptions: { // опционально limit: 500, // максимум на странице expandLimit: 50, // с expand concurrencyLimit: 5 // одновременных запросов } }); ``` -------------------------------- ### Run Tests with Bun Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/CONTRIBUTING.md Execute all project tests using this command. This is crucial for verifying code changes and additions. ```bash bun run test ``` -------------------------------- ### Get One Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Retrieve a single entity by its ID, with options to expand related data. ```APIDOC ## Get One ### Description Retrieve a single entity by its ID, with options to expand related data. ### Code Example ```typescript const counterparty = await moysklad.counterparty.get("id", { expand: { owner: { group: true } } }); ``` ``` -------------------------------- ### Upsert Operation Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/README.md Example for creating a new entity or updating an existing one if it already exists. ```APIDOC ## Upsert Operation ### Upsert Entity Creates a new entity or updates an existing one based on the provided metadata and data. ```typescript const result = await moysklad.counterparty.upsert({ meta: { href: "...", type: "counterparty", mediaType: "application/json" }, name: "Новое имя" }); ``` ``` -------------------------------- ### Create Demand with Metadata Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/07-types-catalog.md Shows how to create a demand document by providing metadata for associated entities like agent and organization. ```typescript import { Entity, MediaType } from "moysklad-ts"; // Для использования в API требуется мета-информация const demand = await moysklad.demand.create({ agent: { meta: { href: "https://api.moysklad.ru/api/remap/1.2/entity/counterparty/abc-123", type: Entity.Counterparty, mediaType: MediaType.Json } }, organization: { meta: { href: "https://api.moysklad.ru/api/remap/1.2/entity/organization/def-456", type: Entity.Organization, mediaType: MediaType.Json } } }); ``` -------------------------------- ### Create Document with Wizard Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/06-endpoints-reference.md Automates the filling of document fields based on a template. Specify the action type and a related document. ```typescript const filled = await moysklad.wizard.create({ action: "DEMAND", customerOrder: { meta: { href: "..." } } }); ``` -------------------------------- ### Get List Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Retrieve a paginated list of entities with options for filtering, ordering, and expanding related data. ```APIDOC ## Get List ### Description Retrieve a paginated list of entities with options for filtering, ordering, and expanding related data. ### Code Example ```typescript const { rows, meta } = await moysklad.counterparty.list({ pagination: { limit: 10, offset: 0 }, filter: { name: { sw: "ООО" } }, order: { field: "name", direction: "asc" }, expand: { owner: true } }); ``` ``` -------------------------------- ### Get Entity Count Source: https://github.com/monsterdeveloper/moysklad-ts/blob/main/_autodocs/10-quick-reference.md Retrieve the total number of entities. The `meta.size` property contains the total count. ```typescript const { meta } = await moysklad.counterparty.size(); console.log(meta.size); // Общее количество ```