@bitrix24/b24jssdk
Version:
Bitrix24 REST API JavaScript SDK
1 lines • 9.8 kB
Source Map (JSON)
{"version":3,"file":"call-list.cjs","sources":["../../../../../src/core/actions/v2/call-list.ts"],"sourcesContent":["import type { TypeCallParams, TypeCallParamsV2 } from '../../../types/http'\nimport type { AjaxResult } from '../../http/ajax-result'\nimport { AbstractAction } from '../abstract-action'\nimport { Result } from '../../result'\n\nexport type ActionCallListV2 = {\n method: string\n params?: Omit<TypeCallParamsV2, 'start' | 'order'>\n idKey?: string\n cursorIdKey?: string\n customKeyForResult?: string\n requestId?: string\n}\n\n/**\n * Fast data retrieval without counting the total number of records. `restApi:v2`\n *\n * Iterates through all pages of a v2 list method using cursor-based pagination (ordering and\n * filtering by the item id) and collects every item into a single array returned as a `Result`.\n * Unlike `FetchListV2`, which yields pages one by one via an async generator, this class waits\n * for all pages to finish and returns the complete dataset in one call.\n */\nexport class CallListV2 extends AbstractAction {\n /**\n * Fast data retrieval without counting the total number of records.\n *\n * @template T - The type of the elements of the returned array (default is `unknown`).\n *\n * @param {ActionCallListV2} options - parameters for executing the request.\n * - `method: string` - The name of the REST API method that returns a list of data (for example: `crm.item.list`, `tasks.task.list`)\n * - `params?: Omit<TypeCallParamsV2, 'start' | 'order'>` - Request parameters, excluding the `start` and `order` parameters,\n * since the method is designed to obtain all data in one call.\n * Note: Use `filter`, `order`, and `select` to control the selection.\n * - `idKey?: string` - The name of the id field as it appears in each RESPONSE item; its value\n * drives the cursor. Default is 'ID' (uppercase). For methods that return a lowercase /\n * camelCase id (for example `tasks.task.list` returns `id`), set `idKey: 'id'`.\n * - `cursorIdKey?: string` - The field name used in the REQUEST for `order` and the `>` page\n * filter. Defaults to `idKey`. Set it only when the sortable / filterable field name differs\n * from the response field name — e.g. `tasks.task.list` sorts and filters by `ID` (uppercase)\n * but returns `id` (lowercase): pass `idKey: 'id', cursorIdKey: 'ID'`.\n * - `customKeyForResult?: string` - A custom key indicating that the response REST API will be\n * grouped by this field.\n * Example: `items` to group a list of CRM items.\n * - `requestId?: string` - Unique request identifier for tracking. Used for query deduplication and debugging.\n *\n * @returns {Promise<Result<T[]>>} A promise that resolves to the result of an REST API call.\n *\n * @example\n * import { EnumCrmEntityTypeId, Text } from '@bitrix24/b24jssdk'\n *\n * interface CrmItem { id: number, title: string }\n * const sixMonthAgo = new Date()\n * sixMonthAgo.setMonth((new Date()).getMonth() - 6)\n * sixMonthAgo.setHours(0, 0, 0)\n * const response = await b24.actions.v2.callList.make<CrmItem>({\n * method: 'crm.item.list',\n * params: {\n * entityTypeId: EnumCrmEntityTypeId.company,\n * filter: {\n * '=%title': 'A%',\n * '>=createdTime': Text.toB24Format(sixMonthAgo) // created at least 6 months ago\n * },\n * select: ['id', 'title']\n * },\n * idKey: 'id',\n * customKeyForResult: 'items',\n * requestId: 'list-123'\n * })\n * if (!response.isSuccess) {\n * throw new Error(`Problem: ${response.getErrorMessages().join('; ')}`)\n * }\n * const list = response.getData()\n * console.log(`Result: ${list?.length}`) // Number of items received\n */\n public override async make<T = unknown>(options: ActionCallListV2): Promise<Result<T[]>> {\n const batchSize = 50\n const result: Result<T[]> = new Result()\n\n const idKey = options?.idKey ?? 'ID'\n const cursorIdKey = options?.cursorIdKey ?? idKey\n const customKeyForResult = options?.customKeyForResult ?? null\n const params = options?.params ?? {}\n\n // Warn and strip user-provided `order` — cursor pagination requires ordering by cursorIdKey only\n if ('order' in params && params['order']) {\n this._logger.warning('callList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.').catch(() => {})\n }\n\n const moreIdKey = `>${cursorIdKey}`\n const { order: _ignoredOrder, ...restParams } = params as TypeCallParams\n const requestParams: TypeCallParams = {\n ...restParams,\n order: { [cursorIdKey]: 'ASC' },\n filter: { ...(params['filter'] || {}), [moreIdKey]: 0 },\n start: -1\n }\n\n let allItems: T[] = []\n\n while (true) {\n const response: AjaxResult<T> = await this._b24.actions.v2.call.make<T>({\n method: options.method,\n params: requestParams,\n requestId: options.requestId\n })\n\n if (!response.isSuccess) {\n this._logger.error('callFastListMethod', {\n method: options.method,\n requestId: options.requestId,\n messages: response.getErrorMessages()\n }).catch(() => {})\n for (const [index, error] of response.errors) {\n result.addError(error, index)\n }\n break\n }\n const responseData = response.getData()\n if (!responseData) {\n break\n }\n\n const resultData: T[] = null === customKeyForResult\n ? responseData.result as T[]\n : (responseData.result as any)[customKeyForResult] as T[]\n\n if (resultData.length === 0) {\n break\n }\n\n allItems = [...allItems, ...resultData]\n\n if (resultData.length < batchSize) {\n break\n }\n\n // Update the filter for the next iteration\n const lastItem = resultData[resultData.length - 1] as Record<string, any>\n const cursorValue = lastItem ? Number.parseInt(lastItem[idKey], 10) : Number.NaN\n if (Number.isFinite(cursorValue)) {\n requestParams.filter[moreIdKey] = cursorValue\n } else {\n // A full page came back, yet no usable numeric cursor id could be read from\n // its items via `idKey` — almost always an `idKey` that doesn't match the\n // response field (e.g. a request that sorts by `ID` while the response\n // carries a lowercase `id`). Without a cursor we can't advance, so stop and\n // tell the caller how to fix it instead of silently truncating.\n this._logger.warning(`callList.make: pagination stops here — no numeric id could be read from the returned items via idKey \"${idKey}\". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`).catch(() => {})\n break\n }\n }\n\n return result.setData(allItems)\n }\n}\n"],"names":["AbstractAction","result","Result"],"mappings":";;;;;;;;;;;;;;;AAsBO,MAAM,mBAAmBA,6BAAA,CAAe;AAAA,EAtB/C;AAsB+C,IAAA,MAAA,CAAA,IAAA,EAAA,YAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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