bx-rest 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,53 @@
1
+ export interface BXRestApiErrorDetails {
2
+ /**
3
+ * HTTP status of the portal response. `undefined` when the error came in
4
+ * the body of a successful (2xx) response.
5
+ */
6
+ status?: number;
7
+ /** REST method that failed, e.g. `crm.deal.get`. */
8
+ method?: string;
9
+ /**
10
+ * The original error, e.g. the `AxiosError` — its `response.data` holds
11
+ * the full response body (including REST v3 `validation`).
12
+ */
13
+ cause?: unknown;
14
+ }
1
15
  /**
2
- * Thrown by `.res()` when called with `{ throwOnApiError: true }` and the
3
- * Bitrix REST call resolves as a Bitrix-level API error, e.g.
4
- * `INSUFFICIENT_SCOPE` or `expired_token`.
16
+ * A Bitrix-level API error, e.g. `INSUFFICIENT_SCOPE` or `expired_token`.
5
17
  *
6
- * By default `.res()` resolves such responses as `undefined` instead of
7
- * throwing — see the "Error handling" section of the README.
18
+ * `.res()` fails with it whenever the portal answers with a Bitrix error and
19
+ * a non-2xx HTTP status — which is how Bitrix sends most of its errors. When
20
+ * the error comes in the body of a 2xx response, `.res()` resolves as
21
+ * `undefined` by default and fails with it only with
22
+ * `{ throwOnApiError: true }` — see the "Error handling" section of the README.
8
23
  */
9
24
  export declare class BXRestApiError extends Error {
10
25
  error: string | undefined;
11
26
  error_description: string | undefined;
12
- constructor(error: string | undefined, error_description: string | undefined);
27
+ readonly status: number | undefined;
28
+ readonly method: string | undefined;
29
+ constructor(error: string | undefined, error_description: string | undefined, details?: BXRestApiErrorDetails);
13
30
  }
31
+ /**
32
+ * Recognises a Bitrix error body: REST v2 `{ error, error_description }` and
33
+ * REST v3 `{ error: { code, message } }`. Returns `undefined` for anything
34
+ * else — a success payload, an HTML page from a proxy, an empty body.
35
+ *
36
+ * An empty `error` still counts: Bitrix answers e.g. `crm.deal.get` for a
37
+ * missing ID with `{ error: '', error_description: 'Not found' }`.
38
+ */
39
+ export declare function parseBXRestErrorBody(body: unknown): {
40
+ error: string;
41
+ error_description: string | undefined;
42
+ } | undefined;
43
+ /**
44
+ * Turns an HTTP failure into a `BXRestApiError` when the portal answered with
45
+ * a Bitrix error body. Bitrix sends most errors with a non-2xx status
46
+ * (401 `expired_token`, 404 `ERROR_METHOD_NOT_FOUND`, 503
47
+ * `QUERY_LIMIT_EXCEEDED`, 400 "Not found" from `crm.*.get`, ...), and axios
48
+ * rejects on those.
49
+ *
50
+ * Returns `undefined` for network errors and for responses that are not a
51
+ * Bitrix error body, so the caller can keep its own handling for them.
52
+ */
53
+ export declare function bxRestApiErrorFromHttp(err: unknown, method: string): BXRestApiError | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bx-rest",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Bitrix24 REST API client and TypeScript SDK for Angular, Vue and browser apps",
5
5
  "keywords": [
6
6
  "bitrix",
package/rest/base.d.ts CHANGED
@@ -29,5 +29,5 @@ export declare class BXRest {
29
29
  readonly socialNetWork: BXRestSocialNetWork;
30
30
  readonly pull: BXRestPull;
31
31
  profile(): import("rxjs").Observable<import("../typification/rest/base").iBXRestAnswer<iBXRestProfileHttp> | undefined>;
32
- batch<T>(param: iBXRestParamBatch): import("rxjs").Observable<import("../typification/rest/base").iBXRestAnswer<iBXRestBatch<T>> | undefined>;
32
+ batch<T>(param: iBXRestParamBatch, headers?: Record<string, string>): import("rxjs").Observable<import("../typification/rest/base").iBXRestAnswer<iBXRestBatch<T>> | undefined>;
33
33
  }
@@ -2,6 +2,7 @@ import { Observable } from 'rxjs';
2
2
  import { HttpServices } from './http';
3
3
  import { iBatchRequestAnswer, iBatchRequestParam, iBatchRequestParamArr, iBatchRequestParamHttp, keyBatch } from '../../typification/rest/batch/batchRequestParam';
4
4
  import { iBXRestAnswer } from '../../typification/rest/base/answer';
5
+ import { iHttpParamSettings } from '../../typification/rest/settings';
5
6
  export declare class HttpBXServices extends HttpServices {
6
7
  /**
7
8
  * Не считайте этот метод образцом/финальным API.
@@ -17,17 +18,27 @@ export declare class HttpBXServices extends HttpServices {
17
18
  *
18
19
  * @param name
19
20
  * @param params
21
+ * @param restApi
22
+ * @param headers заголовки только для этого запроса, поверх `BXRestSettings.headers`
20
23
  */
21
- post<T>(name: string[], params?: any, restApi?: boolean): Observable<iBXRestAnswer<T> | undefined>;
24
+ post<T>(name: string[], params?: any, restApi?: boolean, headers?: Record<string, string>): Observable<iBXRestAnswer<T> | undefined>;
22
25
  /**
23
26
  * Второстепенный метод для запросов. По возможности лучше не использовать
24
27
  *
25
28
  * @param name
26
29
  * @param params
30
+ * @param headers заголовки только для этого запроса, поверх `BXRestSettings.headers`
27
31
  */
28
- get<T>(name: string[], params?: any): Observable<iBXRestAnswer<T> | undefined>;
29
- httpPost<T>(url: string, params?: any): Observable<T | undefined>;
30
- httpGet<T>(url: string, params?: any): Observable<T | undefined>;
32
+ get<T>(name: string[], params?: any, headers?: Record<string, string>): Observable<iBXRestAnswer<T> | undefined>;
33
+ httpPost<T>(url: string, params?: any, settings?: iHttpParamSettings, headers?: Record<string, string>): Observable<T | undefined>;
34
+ httpGet<T>(url: string, params?: any, settings?: iHttpParamSettings, headers?: Record<string, string>): Observable<T | undefined>;
35
+ /**
36
+ * Заголовки запроса: `BXRestSettings.headers`, поверх них — заголовки
37
+ * конкретного запроса, поверх всего — `required`. В `required` идёт
38
+ * `Content-Type`: от него зависит, как сервер разберёт тело, поэтому
39
+ * пользовательские заголовки его не перебивают.
40
+ */
41
+ private buildHeaders;
31
42
  serializeBitrixParams(params: unknown): string;
32
43
  getNameMethod(arr: string[]): string;
33
44
  }
@@ -21,6 +21,11 @@ export declare class SessionKeyServices {
21
21
  * сохраняется историческое поведение: включаем только для `auth.key === 'OAuth2'`.
22
22
  */
23
23
  getWithCredentials(): boolean;
24
+ /**
25
+ * Статичные заголовки из `BXRestSettings.headers` — копия, чтобы правка
26
+ * результата не меняла сами настройки.
27
+ */
28
+ getHeaders(): Record<string, string>;
24
29
  getSessid(): string;
25
30
  getAuthParams(): string | undefined;
26
31
  getCheckAuthParamsIsOn(): boolean;
@@ -4,10 +4,13 @@ import { HttpBXServices } from '../../http/HttpBX';
4
4
  import { ReturnTypeNavvy } from '../navvy-support';
5
5
  export interface BXRestResOptions {
6
6
  /**
7
- * When `true`, a Bitrix-level API error (`{ error, error_description }`,
8
- * e.g. `INSUFFICIENT_SCOPE`, `expired_token`) makes the `Observable`
9
- * returned by `.res()` error out with a `BXRestApiError` instead of
10
- * resolving with `undefined`.
7
+ * When `true`, a Bitrix-level API error that comes in the body of a 2xx
8
+ * response makes the `Observable` returned by `.res()` error out with a
9
+ * `BXRestApiError` instead of resolving with `undefined`.
10
+ *
11
+ * Errors that Bitrix sends with a non-2xx HTTP status (most of them, e.g.
12
+ * `expired_token`, `INSUFFICIENT_SCOPE`) fail with `BXRestApiError`
13
+ * regardless of this option.
11
14
  *
12
15
  * Default: `false` (preserves the historical `.res()` behaviour).
13
16
  */
@@ -19,8 +22,19 @@ export declare abstract class NavvyPagBase<T, R, P> {
19
22
  protected map: ((param: T | undefined) => R | undefined) | undefined;
20
23
  protected restApi: boolean;
21
24
  protected readonly http: HttpBXServices;
25
+ protected requestHeaders?: Record<string, string>;
22
26
  pageSize: number;
23
27
  constructor(url: string[], param: P, map?: ((param: T | undefined) => R | undefined) | undefined, restApi?: boolean);
28
+ /**
29
+ * HTTP-заголовки только для этого запроса — поверх `BXRestSettings.headers`
30
+ * (при совпадении имени побеждает значение отсюда). Повторные вызовы
31
+ * дополняют уже заданные заголовки. Действует на `.res()`, `.resVanilla()`,
32
+ * `.mapForVanilla()` и на все batch-запросы `.resAll()`.
33
+ *
34
+ * @example
35
+ * bx.crm.deal.list({ ... }).withHeaders({ 'X-Request-Source': 'report' }).resAll()
36
+ */
37
+ withHeaders(headers: Record<string, string>): this;
24
38
  resVanilla(): Observable<iBXRestAnswer<T> | undefined>;
25
39
  mapForVanilla(): Observable<iBXRestAnswer<ReturnTypeNavvy<T, R>> | undefined>;
26
40
  res(options?: BXRestResOptions): Observable<ReturnTypeNavvy<T, R> | undefined>;
@@ -17,4 +17,11 @@ export interface iBXRestSettings {
17
17
  * а браузер должен приложить cookie сессии этого прокси (не Bitrix24).
18
18
  */
19
19
  withCredentials?: boolean;
20
+ /**
21
+ * Статичные HTTP-заголовки, которые прикладываются к каждому запросу,
22
+ * например `{ 'X-Bitrix-App': 'smart-process-pro' }`. Для одного запроса
23
+ * их можно дополнить или перебить через `.withHeaders()`. `Content-Type`
24
+ * библиотека всегда выставляет сама — от него зависит формат тела запроса.
25
+ */
26
+ headers?: Record<string, string>;
20
27
  }