bx-rest 0.24.4 → 0.25.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.
- package/README.en.md +578 -0
- package/README.md +94 -92
- package/package.json +6 -1
package/README.en.md
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
🇷🇺 [Русский](README.md) | 🇬🇧 **English**
|
|
2
|
+
|
|
3
|
+
# bx-rest - Bitrix24 REST API client for TypeScript, Angular, Vue and React
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/bx-rest)
|
|
6
|
+
[](https://www.npmjs.com/package/bx-rest)
|
|
7
|
+
[](https://github.com/Aricatofuka/bx-rest/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
`bx-rest` is a TypeScript SDK for the Bitrix24 REST API. It helps call BX24 REST methods, work with auth tokens, sessid, OAuth2, pagination, mappers and typed API requests.
|
|
10
|
+
|
|
11
|
+
Also known as: Bitrix24 REST client, BX24 REST SDK, Bitrix24 API client, Bitrix REST TypeScript library.
|
|
12
|
+
|
|
13
|
+
## Contents
|
|
14
|
+
|
|
15
|
+
- [Install](#install)
|
|
16
|
+
- [Requirements](#requirements)
|
|
17
|
+
- [Quick Start](#quick-start)
|
|
18
|
+
- [Result modes](#result-modes)
|
|
19
|
+
- [Authentication and OAuth2](#authentication-and-oauth2)
|
|
20
|
+
- [Error handling](#error-handling)
|
|
21
|
+
- [Usage in Angular](#usage-in-angular)
|
|
22
|
+
- [SessionKeyServices](#sessionkeyservices)
|
|
23
|
+
- [Usage in Vue](#usage-in-vue)
|
|
24
|
+
- [Usage in React](#usage-in-react)
|
|
25
|
+
- [Custom REST methods](#custom-rest-methods)
|
|
26
|
+
- [Mapper](#mapper)
|
|
27
|
+
- [A custom method with `simple()`](#a-custom-method-with-simple)
|
|
28
|
+
- [A paginated custom method with `pagNav()`](#a-paginated-custom-method-with-pagnav)
|
|
29
|
+
- [Specific methods](#specific-methods)
|
|
30
|
+
- [`tasks.task.list`](#taskstasklist)
|
|
31
|
+
- [Date parsing](#date-parsing)
|
|
32
|
+
- [Future features](#future-features)
|
|
33
|
+
- [License](#license)
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```shell
|
|
38
|
+
npm install bx-rest
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Requirements
|
|
42
|
+
|
|
43
|
+
- **Module format:** `bx-rest` ships ES modules only — there is no CommonJS/`require` build. Use it from an ESM-aware bundler (Angular CLI, Vite, webpack 5+, Next.js, ...) or a native `import()`. Plain `require('bx-rest')` (older Jest configs without ESM support, `ts-node` in CJS mode, etc.) will not resolve the package.
|
|
44
|
+
- **TypeScript:** developed against TypeScript 5.5+. `strict` mode is recommended — the bundled typification relies on it to give accurate field types.
|
|
45
|
+
- **RxJS:** `rxjs` (^7.8) is a regular dependency bundled with the package, not a `peerDependency`, so no specific host version is enforced. Every REST call returns an RxJS `Observable`.
|
|
46
|
+
- **Frameworks:** the Angular, Vue and React examples below are written against Angular 18/19, Vue 3 and React 18+ APIs (the versions this library is built and tested with). None of these frameworks are declared as `peerDependencies` — `bx-rest` has no hard dependency on any of them — but the DI/composition patterns shown assume those major versions.
|
|
47
|
+
- **Environment:** `bx-rest` is browser-oriented. The `cookies`/`localStorage`/`sessid` auth sources and `SessionKeyServices` read `window`, `document` and `localStorage` directly. In a server-side-rendered app (Angular Universal, Next.js, etc.) only exercise those code paths in the browser (e.g. behind `isPlatformBrowser`/`typeof window !== 'undefined'` guards), or use an auth source that doesn't touch browser globals, such as `source: () => accessToken` or `source: 'off'`.
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
Configure the portal URL and an access-token source once, then create a client and subscribe to the returned RxJS `Observable`. Use a complete URL including `https://`.
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { firstValueFrom } from 'rxjs'
|
|
55
|
+
import { BXRestNavvy, BXRestSettings } from 'bx-rest'
|
|
56
|
+
|
|
57
|
+
const accessToken = 'YOUR_ACCESS_TOKEN'
|
|
58
|
+
|
|
59
|
+
BXRestSettings.update({
|
|
60
|
+
auth: {
|
|
61
|
+
source: () => accessToken,
|
|
62
|
+
key: 'auth'
|
|
63
|
+
},
|
|
64
|
+
urls: {
|
|
65
|
+
source: 'string',
|
|
66
|
+
key: 'https://example.bitrix24.com',
|
|
67
|
+
additional_part: 'rest'
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const bxRest = new BXRestNavvy()
|
|
72
|
+
|
|
73
|
+
const deals = await firstValueFrom(
|
|
74
|
+
bxRest.crm.deal.list({
|
|
75
|
+
select: ['ID', 'TITLE'],
|
|
76
|
+
filter: {},
|
|
77
|
+
start: 0
|
|
78
|
+
}).res()
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
console.log(deals)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Do not hardcode or commit a production access token. Pass it from your application's authorization flow, server response or secure runtime configuration.
|
|
85
|
+
|
|
86
|
+
### Result modes
|
|
87
|
+
|
|
88
|
+
REST calls are lazy: the request starts when the returned `Observable` is subscribed to or passed to `firstValueFrom`.
|
|
89
|
+
|
|
90
|
+
| Method | Result |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| `.res(options?)` | Unwraps the Bitrix response and applies the configured mapper. For paginated methods it returns the current page. |
|
|
93
|
+
| `.resAll()` | Loads and combines every page. Available on paginated Navvy helpers. |
|
|
94
|
+
| `.resVanilla()` | Returns the raw Bitrix response, including fields such as `result`, `total` and `next`. |
|
|
95
|
+
| `.mapForVanilla()` | Keeps the raw response envelope but applies the mapper to its `result`. |
|
|
96
|
+
|
|
97
|
+
`.res()` accepts an optional options object:
|
|
98
|
+
|
|
99
|
+
| Option | Default | Effect |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| `throwOnApiError` | `false` | When `true`, a Bitrix-level API error makes the returned `Observable` error out with a `BXRestApiError` instead of resolving with `undefined`. See [Error handling](#error-handling). |
|
|
102
|
+
|
|
103
|
+
## Authentication and OAuth2
|
|
104
|
+
|
|
105
|
+
`auth.source` controls where credentials are read from. `auth.key` controls the request parameter name, except for the special `OAuth2` cookie-credentials mode.
|
|
106
|
+
|
|
107
|
+
| Scenario | `auth.source` | `auth.key` | Behaviour |
|
|
108
|
+
| --- | --- | --- | --- |
|
|
109
|
+
| Access token from application state | `() => accessToken` | `auth` | Calls the function before each request and sends its value in the `auth` parameter. Recommended for OAuth2 access tokens managed by the application. |
|
|
110
|
+
| Access token in local storage | `localStorage` | `auth` | Reads `localStorage["auth"]` and sends it as `auth`. |
|
|
111
|
+
| Access token in a cookie | `cookies` | `auth` | Reads the `auth` cookie and sends it as `auth`. |
|
|
112
|
+
| Embedded Bitrix page / local session | `cookies` | `sessid` | Tries `window.BX.bitrix_sessid()`, the `sessid` query parameter, `localStorage.sessid`, then the `auth` cookie. Sends the resolved value as `sessid`. |
|
|
113
|
+
| Incoming webhook or URL that already contains authorization | `off` | Any value | Skips credential lookup and does not add an authorization parameter. |
|
|
114
|
+
| Cookie-based credential request | Any source returning a non-empty value | `OAuth2` | Does not append the resolved value to request params and enables Axios `withCredentials`. Use only when the portal and CORS policy support credential cookies. |
|
|
115
|
+
|
|
116
|
+
For a regular Bitrix OAuth2 `access_token`, use `auth.key: 'auth'` and provide the current token through a function or `localStorage`. The special `auth.key: 'OAuth2'` mode is for credential cookies; it does not send an OAuth access token by itself.
|
|
117
|
+
|
|
118
|
+
For an incoming webhook URL, keep the full webhook path in `urls.key`, set `additional_part` to an empty string and disable additional authorization:
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
BXRestSettings.update({
|
|
122
|
+
auth: {
|
|
123
|
+
source: 'off',
|
|
124
|
+
key: 'auth'
|
|
125
|
+
},
|
|
126
|
+
urls: {
|
|
127
|
+
source: 'string',
|
|
128
|
+
key: 'https://example.bitrix24.com/rest/1/WEBHOOK_CODE',
|
|
129
|
+
additional_part: ''
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Error handling
|
|
135
|
+
|
|
136
|
+
`bx-rest` surfaces two different kinds of failure, and `.res()` only reacts to one of them.
|
|
137
|
+
|
|
138
|
+
| Failure | When it happens | How it surfaces on `.res()` |
|
|
139
|
+
| --- | --- | --- |
|
|
140
|
+
| Transport / configuration errors — network failure, missing auth, missing base URL | Before or during the HTTP call | The returned `Observable` errors. Handle it with RxJS `catchError` or the `error` callback of `subscribe()`. |
|
|
141
|
+
| Bitrix API errors — `{ error, error_description }`, e.g. `INSUFFICIENT_SCOPE`, `expired_token` | HTTP 200 response whose body is not a success payload | By default, `.res()` resolves normally with `undefined` — **it does not throw**. Pass `{ throwOnApiError: true }` to make it throw a `BXRestApiError` instead. |
|
|
142
|
+
|
|
143
|
+
Because a Bitrix-level error resolves as `undefined` rather than as an `Observable` error by default, don't rely on plain `.res()` alone to tell "no records" apart from "the call failed". You have two options.
|
|
144
|
+
|
|
145
|
+
**Option 1 — opt in to throwing with `.res({ throwOnApiError: true })`.** The `Observable` errors with a `BXRestApiError`, exposing `error` and `error_description`, so it can be handled alongside transport errors in a single `catchError`/`error` callback:
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
import { BXRestNavvy, BXRestApiError } from 'bx-rest'
|
|
149
|
+
|
|
150
|
+
const bxRest = new BXRestNavvy()
|
|
151
|
+
|
|
152
|
+
bxRest.crm.deal.list({
|
|
153
|
+
select: ['ID', 'TITLE'],
|
|
154
|
+
filter: {},
|
|
155
|
+
start: 0
|
|
156
|
+
}).res({ throwOnApiError: true }).subscribe({
|
|
157
|
+
next: deals => console.log(deals),
|
|
158
|
+
error: err => {
|
|
159
|
+
if (err instanceof BXRestApiError) {
|
|
160
|
+
console.error('Bitrix API error:', err.error, err.error_description)
|
|
161
|
+
} else {
|
|
162
|
+
console.error('Request failed:', err.message)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
**Option 2 — keep the default and check the raw response.** Call `.resVanilla()` instead and check the response with the exported `isBXRestAnswerSuccess()` type guard:
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
import { firstValueFrom } from 'rxjs'
|
|
172
|
+
import { BXRestNavvy, isBXRestAnswerSuccess } from 'bx-rest'
|
|
173
|
+
|
|
174
|
+
const bxRest = new BXRestNavvy()
|
|
175
|
+
|
|
176
|
+
const answer = await firstValueFrom(
|
|
177
|
+
bxRest.crm.deal.list({
|
|
178
|
+
select: ['ID', 'TITLE'],
|
|
179
|
+
filter: {},
|
|
180
|
+
start: 0
|
|
181
|
+
}).resVanilla()
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
if (!answer || !isBXRestAnswerSuccess(answer)) {
|
|
185
|
+
console.error('Bitrix API error:', answer?.error, answer?.error_description)
|
|
186
|
+
} else {
|
|
187
|
+
console.log(answer.result)
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Regardless of `throwOnApiError`, transport-level failures always propagate as `Observable` errors and can be caught the usual RxJS way:
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
bxRest.crm.deal.list({
|
|
195
|
+
select: ['ID', 'TITLE'],
|
|
196
|
+
filter: {},
|
|
197
|
+
start: 0
|
|
198
|
+
}).res().subscribe({
|
|
199
|
+
next: deals => console.log(deals),
|
|
200
|
+
error: err => console.error('Request failed:', err.message)
|
|
201
|
+
})
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Usage in Angular
|
|
205
|
+
|
|
206
|
+
Register the public clients and `Navvy` when you want to inject them into Angular services or components:
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
import { ApplicationConfig, Provider } from '@angular/core'
|
|
210
|
+
import {
|
|
211
|
+
BXRestMap,
|
|
212
|
+
BXRestNavvy,
|
|
213
|
+
BXRestRequest,
|
|
214
|
+
Navvy
|
|
215
|
+
} from 'bx-rest'
|
|
216
|
+
|
|
217
|
+
export const BXRestNavvyProvider: Provider = {
|
|
218
|
+
provide: BXRestNavvy,
|
|
219
|
+
useFactory: () => new BXRestNavvy()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export const BXRestMapProvider: Provider = {
|
|
223
|
+
provide: BXRestMap,
|
|
224
|
+
useFactory: () => new BXRestMap()
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export const BXRestRequestProvider: Provider = {
|
|
228
|
+
provide: BXRestRequest,
|
|
229
|
+
useFactory: () => new BXRestRequest()
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export const NavvyProvider: Provider = {
|
|
233
|
+
provide: Navvy,
|
|
234
|
+
useFactory: () => new Navvy()
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export const appConfig: ApplicationConfig = {
|
|
238
|
+
providers: [
|
|
239
|
+
BXRestNavvyProvider,
|
|
240
|
+
BXRestMapProvider,
|
|
241
|
+
BXRestRequestProvider,
|
|
242
|
+
NavvyProvider
|
|
243
|
+
]
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Example component:
|
|
248
|
+
|
|
249
|
+
```typescript
|
|
250
|
+
import { Component, inject } from '@angular/core'
|
|
251
|
+
import { BXRestNavvy } from 'bx-rest'
|
|
252
|
+
|
|
253
|
+
@Component({
|
|
254
|
+
selector: 'app-list',
|
|
255
|
+
template: ''
|
|
256
|
+
})
|
|
257
|
+
export class ListComponent {
|
|
258
|
+
private readonly bxRest = inject(BXRestNavvy)
|
|
259
|
+
|
|
260
|
+
readonly listElements$ = this.bxRest.lists.element.get({
|
|
261
|
+
IBLOCK_TYPE_ID: 'lists',
|
|
262
|
+
IBLOCK_ID: 150,
|
|
263
|
+
FILTER: {
|
|
264
|
+
'>ID': 0
|
|
265
|
+
}
|
|
266
|
+
}).res()
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
## SessionKeyServices
|
|
271
|
+
|
|
272
|
+
`SessionKeyServices` is available from the public API and can be used when you need to inspect the current authorization data before making REST requests.
|
|
273
|
+
|
|
274
|
+
```typescript
|
|
275
|
+
import { BXRestSettings, SessionKeyServices, SessionKeyError } from 'bx-rest'
|
|
276
|
+
|
|
277
|
+
BXRestSettings.update({
|
|
278
|
+
auth: {
|
|
279
|
+
source: 'cookies',
|
|
280
|
+
key: 'auth'
|
|
281
|
+
},
|
|
282
|
+
urls: {
|
|
283
|
+
source: 'string',
|
|
284
|
+
key: 'https://example.bitrix24.com',
|
|
285
|
+
additional_part: 'rest'
|
|
286
|
+
}
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
const session = new SessionKeyServices()
|
|
290
|
+
|
|
291
|
+
const auth = session.getAuthParams()
|
|
292
|
+
const authKey = session.getKeyAuth()
|
|
293
|
+
|
|
294
|
+
if (!auth && session.getCheckAuthParamsIsOn()) {
|
|
295
|
+
const error = session.getAuthError('manual auth check')
|
|
296
|
+
if (error instanceof SessionKeyError) {
|
|
297
|
+
console.error(error.message)
|
|
298
|
+
}
|
|
299
|
+
throw error
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
session.getBaseUrl().subscribe((baseUrl) => {
|
|
303
|
+
if (!baseUrl) {
|
|
304
|
+
throw session.getBaseUrlError('manual base url check')
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
console.log({ authKey, auth, baseUrl })
|
|
308
|
+
})
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
## Usage in Vue
|
|
312
|
+
|
|
313
|
+
```typescript
|
|
314
|
+
import type { Plugin } from 'vue'
|
|
315
|
+
import { BXRestSettings, BXRestMap, BXRestNavvy, BXRestRequest } from 'bx-rest'
|
|
316
|
+
|
|
317
|
+
const bxRestPlugin: Plugin = {
|
|
318
|
+
install(app) {
|
|
319
|
+
BXRestSettings.update({
|
|
320
|
+
auth: {
|
|
321
|
+
source: 'cookies',
|
|
322
|
+
key: 'auth'
|
|
323
|
+
},
|
|
324
|
+
urls: {
|
|
325
|
+
source: 'string',
|
|
326
|
+
key: 'https://example.bitrix24.com',
|
|
327
|
+
additional_part: 'rest'
|
|
328
|
+
}
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
app.config.globalProperties.$bxRestNavvy = new BXRestNavvy()
|
|
332
|
+
app.config.globalProperties.$bxRestMap = new BXRestMap()
|
|
333
|
+
app.config.globalProperties.$bxRestRequest = new BXRestRequest()
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export default bxRestPlugin
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
```vue
|
|
341
|
+
import './assets/main.css'
|
|
342
|
+
|
|
343
|
+
import { createApp } from 'vue'
|
|
344
|
+
import App from './App.vue'
|
|
345
|
+
import bxRestPlugin from './bxRestPlugin'
|
|
346
|
+
|
|
347
|
+
const app = createApp(App)
|
|
348
|
+
|
|
349
|
+
app.use(bxRestPlugin)
|
|
350
|
+
|
|
351
|
+
app.mount('#app')
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
## Usage in React
|
|
355
|
+
|
|
356
|
+
Create the client outside the component and unsubscribe when the component is unmounted:
|
|
357
|
+
|
|
358
|
+
```tsx
|
|
359
|
+
import { useEffect, useState } from 'react'
|
|
360
|
+
import { BXRestNavvy } from 'bx-rest'
|
|
361
|
+
|
|
362
|
+
const bxRest = new BXRestNavvy()
|
|
363
|
+
|
|
364
|
+
export function Deals() {
|
|
365
|
+
const [deals, setDeals] = useState<unknown[]>([])
|
|
366
|
+
|
|
367
|
+
useEffect(() => {
|
|
368
|
+
const subscription = bxRest.crm.deal.list({
|
|
369
|
+
select: ['ID', 'TITLE'],
|
|
370
|
+
filter: {},
|
|
371
|
+
start: 0
|
|
372
|
+
}).res().subscribe({
|
|
373
|
+
next: value => setDeals(value ?? []),
|
|
374
|
+
error: error => console.error(error)
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
return () => subscription.unsubscribe()
|
|
378
|
+
}, [])
|
|
379
|
+
|
|
380
|
+
return <pre>{JSON.stringify(deals, null, 2)}</pre>
|
|
381
|
+
}
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
## Custom REST methods
|
|
385
|
+
|
|
386
|
+
`Navvy` is exported from `bx-rest`. In Angular, register the `NavvyProvider` shown above and inject `Navvy` into your custom API service. A method URL is represented as an array and is joined with dots before the request is sent.
|
|
387
|
+
|
|
388
|
+
See the [Bitrix24 documentation](https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=99&LESSON_ID=7985) for registering custom REST methods.
|
|
389
|
+
|
|
390
|
+
### Mapper
|
|
391
|
+
|
|
392
|
+
A mapper is a regular function. It does not need to extend `BXRestMap`.
|
|
393
|
+
|
|
394
|
+
```typescript
|
|
395
|
+
import {
|
|
396
|
+
iBXRestCustomBlogGet,
|
|
397
|
+
iBXRestCustomBlogGetHttp
|
|
398
|
+
} from '../type/blog'
|
|
399
|
+
|
|
400
|
+
export class BXCustomBlogMap {
|
|
401
|
+
static get(
|
|
402
|
+
value: iBXRestCustomBlogGetHttp[] | undefined
|
|
403
|
+
): iBXRestCustomBlogGet[] {
|
|
404
|
+
return (value ?? []).map(item => ({
|
|
405
|
+
id: Number(item.ID),
|
|
406
|
+
title: item.TITLE
|
|
407
|
+
}))
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
### A custom method with `simple()`
|
|
413
|
+
|
|
414
|
+
Use `simple()` when the method returns one response without automatic pagination:
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
import { inject, Injectable } from '@angular/core'
|
|
418
|
+
import { Navvy, partNameMethods as PNM } from 'bx-rest'
|
|
419
|
+
import { BXCustomBlogMap } from '../map/blog'
|
|
420
|
+
import {
|
|
421
|
+
iBXRestCustomBlogGet,
|
|
422
|
+
iBXRestCustomBlogGetHttp,
|
|
423
|
+
iBXRestCustomParamBlogGet
|
|
424
|
+
} from '../type/blog'
|
|
425
|
+
|
|
426
|
+
@Injectable({
|
|
427
|
+
providedIn: 'root'
|
|
428
|
+
})
|
|
429
|
+
export class BXRestNavvyCustomApiBlog {
|
|
430
|
+
private readonly url = {
|
|
431
|
+
get: ['blog', PNM.$get]
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private readonly navvy = inject(Navvy)
|
|
435
|
+
|
|
436
|
+
get(param: iBXRestCustomParamBlogGet) {
|
|
437
|
+
return this.navvy.simple<
|
|
438
|
+
iBXRestCustomBlogGetHttp[],
|
|
439
|
+
iBXRestCustomBlogGet[],
|
|
440
|
+
iBXRestCustomParamBlogGet
|
|
441
|
+
>(
|
|
442
|
+
this.url.get,
|
|
443
|
+
param,
|
|
444
|
+
BXCustomBlogMap.get
|
|
445
|
+
)
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
The returned helper supports `.res()`, `.resVanilla()` and `.mapForVanilla()`.
|
|
451
|
+
|
|
452
|
+
### A paginated custom method with `pagNav()`
|
|
453
|
+
|
|
454
|
+
Use `pagNav()` when the Bitrix response contains an array and standard `start`, `next` and `total` pagination fields. The parameter type must support `start?: number`.
|
|
455
|
+
|
|
456
|
+
```typescript
|
|
457
|
+
import { inject, Injectable } from '@angular/core'
|
|
458
|
+
import { Navvy, partNameMethods as PNM } from 'bx-rest'
|
|
459
|
+
import type { iBXRestPagination } from 'bx-rest/typification/base'
|
|
460
|
+
import { BXCustomBlogMap } from '../map/blog'
|
|
461
|
+
import {
|
|
462
|
+
iBXRestCustomBlogGet,
|
|
463
|
+
iBXRestCustomBlogGetHttp
|
|
464
|
+
} from '../type/blog'
|
|
465
|
+
|
|
466
|
+
export interface iBXRestCustomParamBlogList extends iBXRestPagination {
|
|
467
|
+
filter?: Record<string, unknown>
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
@Injectable({
|
|
471
|
+
providedIn: 'root'
|
|
472
|
+
})
|
|
473
|
+
export class BXRestNavvyCustomApiBlogList {
|
|
474
|
+
private readonly url = {
|
|
475
|
+
list: ['blog', PNM.$list]
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private readonly navvy = inject(Navvy)
|
|
479
|
+
|
|
480
|
+
list(param: iBXRestCustomParamBlogList) {
|
|
481
|
+
return this.navvy.pagNav<
|
|
482
|
+
iBXRestCustomBlogGetHttp,
|
|
483
|
+
iBXRestCustomBlogGet,
|
|
484
|
+
iBXRestCustomParamBlogList
|
|
485
|
+
>(
|
|
486
|
+
this.url.list,
|
|
487
|
+
param,
|
|
488
|
+
BXCustomBlogMap.get
|
|
489
|
+
)
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
The returned helper additionally supports `.resAll()` for loading and combining all pages.
|
|
495
|
+
|
|
496
|
+
## Specific methods
|
|
497
|
+
|
|
498
|
+
### `tasks.task.list`
|
|
499
|
+
|
|
500
|
+
The first generic argument selects built-in task fields. The second adds project-specific user fields:
|
|
501
|
+
|
|
502
|
+
```typescript
|
|
503
|
+
import { BXRestNavvy } from 'bx-rest'
|
|
504
|
+
import type { iBXRestTaskFieldsName } from 'bx-rest/typification/tasks'
|
|
505
|
+
|
|
506
|
+
type SelectedTaskField = Extract<
|
|
507
|
+
iBXRestTaskFieldsName,
|
|
508
|
+
'ID' | 'TITLE' | 'GROUP_ID' | 'TIME_ESTIMATE' | 'CREATED_DATE' | 'CLOSED_DATE' | 'DURATION_FACT' | 'TIME_SPENT_IN_LOGS'
|
|
509
|
+
>
|
|
510
|
+
|
|
511
|
+
type CustomTaskFields = {
|
|
512
|
+
ufListDiscipline: string
|
|
513
|
+
ufListSubdiscipline: string
|
|
514
|
+
ufList1: string
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const selectedTaskFields: SelectedTaskField[] = [
|
|
518
|
+
'ID',
|
|
519
|
+
'TITLE',
|
|
520
|
+
'GROUP_ID',
|
|
521
|
+
'CREATED_DATE'
|
|
522
|
+
]
|
|
523
|
+
|
|
524
|
+
const selectedCustomFields = [
|
|
525
|
+
'UF_LIST_DISCIPLINE',
|
|
526
|
+
'UF_LIST_SUBDISCIPLINE',
|
|
527
|
+
'UF_LIST_1'
|
|
528
|
+
] as const
|
|
529
|
+
|
|
530
|
+
const bxRest = new BXRestNavvy()
|
|
531
|
+
|
|
532
|
+
const tasks$ = bxRest.tasks.task.list<
|
|
533
|
+
SelectedTaskField[],
|
|
534
|
+
CustomTaskFields
|
|
535
|
+
>({
|
|
536
|
+
order: {
|
|
537
|
+
ID: 'DESC'
|
|
538
|
+
},
|
|
539
|
+
filter: {
|
|
540
|
+
CREATED_BY: [1]
|
|
541
|
+
},
|
|
542
|
+
select: [...selectedTaskFields, ...selectedCustomFields],
|
|
543
|
+
start: 0
|
|
544
|
+
}).res()
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
## Date parsing
|
|
548
|
+
|
|
549
|
+
Some Bitrix24 REST fields (notably `calendar.section.get`, `calendar.event.get` and `crm.calllist.*`) return dates as plain strings formatted according to the portal's own date/time settings (Settings → date and time format) — not a fixed ISO format. Because that format is a per-portal setting, `bx-rest` can't know it in advance, so `BXBaseServices.toDate()` (used internally by these mappers) resolves an ambiguous string in three steps, in order:
|
|
550
|
+
|
|
551
|
+
1. **The format you asked for.** If you (or a mapper) pass an explicit `format` (e.g. `'dd.MM.yyyy HH:mm:ss'`), it's tried first, token by token (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`, and their single-letter variants) with the literal separators from the format string.
|
|
552
|
+
2. **A short list of known Bitrix24 formats** (`'dd.MM.yyyy HH:mm:ss'`, `'yyyy-MM-dd HH:mm:ss'`, `'dd.MM.yyyy'`, `'yyyy-MM-dd'`) — tried if step 1 didn't match, since different portals commonly send one of these.
|
|
553
|
+
3. **A positional heuristic**, as a last resort — it locates the year by its unambiguous 4-digit length (whichever end of the date it's on), treats the middle segment as the month (true for both ISO and European-style dates) and reads any separator (`.`, `-`, `/`, space...). It does **not** guess in the one case that's genuinely ambiguous — a purely numeric `MM/dd` vs `dd/MM` order where both segments are ≤ 12 — and it validates ranges (month 1-12, day 1-31, hour/minute/second) rather than letting `Date` silently roll over an out-of-range value into the next month/year.
|
|
554
|
+
|
|
555
|
+
If you already know your portal's exact format, pass it explicitly instead of relying on auto-detection — it's always tried first and skips steps 2-3 entirely. The calendar and call-list mappers accept it as a single optional trailing `dateTimeFormat` argument, and it flows through the corresponding `BXRestNavvy` methods too. Where a mapper also has date-only fields (`calendar.event`'s `EXDATE`/`RRULE.UNTIL`), their format is derived from `dateTimeFormat` by dropping `HH:mm:ss` — day/month/year order is always the same for both on a given portal, so there's nothing extra to pass:
|
|
556
|
+
|
|
557
|
+
```typescript
|
|
558
|
+
import { BXRestNavvy } from 'bx-rest'
|
|
559
|
+
|
|
560
|
+
const bxRest = new BXRestNavvy()
|
|
561
|
+
|
|
562
|
+
// Portal-specific date/time format, e.g. from Settings → date and time format.
|
|
563
|
+
const dateTimeFormat = 'yyyy-MM-dd HH:mm:ss'
|
|
564
|
+
|
|
565
|
+
bxRest.calendar.event.get({ FROM: '01.01.2026', TO: '31.01.2026' }, dateTimeFormat).res()
|
|
566
|
+
bxRest.calendar.section.get({}, dateTimeFormat).res()
|
|
567
|
+
bxRest.crm.callList.get({ ID: 1 }, dateTimeFormat).res()
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
## Future features
|
|
571
|
+
- Auto get token
|
|
572
|
+
- Mappers for normalization types
|
|
573
|
+
|
|
574
|
+
Have a feature request or found a bug? Check [existing issues](https://github.com/Aricatofuka/bx-rest/issues) or open a new one.
|
|
575
|
+
|
|
576
|
+
## License
|
|
577
|
+
|
|
578
|
+
[MIT](https://github.com/Aricatofuka/bx-rest/blob/main/LICENSE) © Aricatofuka
|
package/README.md
CHANGED
|
@@ -1,52 +1,54 @@
|
|
|
1
|
-
|
|
1
|
+
🇷🇺 **Русский** | 🇬🇧 [English](README.en.md)
|
|
2
|
+
|
|
3
|
+
# bx-rest — REST API клиент Bitrix24 для TypeScript, Angular, Vue и React
|
|
2
4
|
|
|
3
5
|
[](https://www.npmjs.com/package/bx-rest)
|
|
4
6
|
[](https://www.npmjs.com/package/bx-rest)
|
|
5
7
|
[](https://github.com/Aricatofuka/bx-rest/blob/main/LICENSE)
|
|
6
8
|
|
|
7
|
-
`bx-rest`
|
|
9
|
+
`bx-rest` — SDK на TypeScript для REST API Bitrix24. Помогает вызывать методы BX24 REST, работать с токенами авторизации, sessid, OAuth2, пагинацией, мапперами и типизированными API-запросами.
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
Также известен как: REST-клиент Bitrix24, BX24 REST SDK, API-клиент Bitrix24, Bitrix REST TypeScript библиотека.
|
|
10
12
|
|
|
11
|
-
##
|
|
13
|
+
## Содержание
|
|
12
14
|
|
|
13
|
-
- [
|
|
14
|
-
- [
|
|
15
|
-
- [
|
|
16
|
-
- [
|
|
17
|
-
- [
|
|
18
|
-
- [
|
|
19
|
-
- [
|
|
15
|
+
- [Установка](#установка)
|
|
16
|
+
- [Требования](#требования)
|
|
17
|
+
- [Быстрый старт](#быстрый-старт)
|
|
18
|
+
- [Режимы результата](#режимы-результата)
|
|
19
|
+
- [Аутентификация и OAuth2](#аутентификация-и-oauth2)
|
|
20
|
+
- [Обработка ошибок](#обработка-ошибок)
|
|
21
|
+
- [Использование в Angular](#использование-в-angular)
|
|
20
22
|
- [SessionKeyServices](#sessionkeyservices)
|
|
21
|
-
- [
|
|
22
|
-
- [
|
|
23
|
-
- [
|
|
23
|
+
- [Использование в Vue](#использование-в-vue)
|
|
24
|
+
- [Использование в React](#использование-в-react)
|
|
25
|
+
- [Кастомные REST-методы](#кастомные-rest-методы)
|
|
24
26
|
- [Mapper](#mapper)
|
|
25
|
-
- [
|
|
26
|
-
- [
|
|
27
|
-
- [
|
|
27
|
+
- [Кастомный метод с `simple()`](#кастомный-метод-с-simple)
|
|
28
|
+
- [Пагинированный кастомный метод с `pagNav()`](#пагинированный-кастомный-метод-с-pagnav)
|
|
29
|
+
- [Специфичные методы](#специфичные-методы)
|
|
28
30
|
- [`tasks.task.list`](#taskstasklist)
|
|
29
|
-
- [
|
|
30
|
-
- [
|
|
31
|
-
- [
|
|
31
|
+
- [Парсинг дат](#парсинг-дат)
|
|
32
|
+
- [Планы на будущее](#планы-на-будущее)
|
|
33
|
+
- [Лицензия](#лицензия)
|
|
32
34
|
|
|
33
|
-
##
|
|
35
|
+
## Установка
|
|
34
36
|
|
|
35
37
|
```shell
|
|
36
38
|
npm install bx-rest
|
|
37
39
|
```
|
|
38
40
|
|
|
39
|
-
##
|
|
41
|
+
## Требования
|
|
40
42
|
|
|
41
|
-
-
|
|
42
|
-
- **TypeScript:**
|
|
43
|
-
- **RxJS:** `rxjs` (^7.8)
|
|
44
|
-
-
|
|
45
|
-
-
|
|
43
|
+
- **Формат модулей:** `bx-rest` поставляется только в виде ES-модулей — сборки CommonJS/`require` нет. Используйте его через ESM-совместимый бандлер (Angular CLI, Vite, webpack 5+, Next.js, ...) или нативный `import()`. Обычный `require('bx-rest')` (старые конфигурации Jest без поддержки ESM, `ts-node` в режиме CJS и т.п.) пакет не разрешит.
|
|
44
|
+
- **TypeScript:** разработан под TypeScript 5.5+. Рекомендуется режим `strict` — встроенная типизация опирается на него для точных типов полей.
|
|
45
|
+
- **RxJS:** `rxjs` (^7.8) — обычная зависимость, поставляемая вместе с пакетом, а не `peerDependency`, поэтому конкретная версия у хоста не требуется. Каждый REST-вызов возвращает RxJS `Observable`.
|
|
46
|
+
- **Фреймворки:** примеры для Angular, Vue и React ниже написаны под API Angular 18/19, Vue 3 и React 18+ (версии, на которых собирается и тестируется библиотека). Ни один из этих фреймворков не объявлен как `peerDependencies` — `bx-rest` не имеет жёсткой зависимости ни от одного из них, — но показанные паттерны DI/композиции рассчитаны именно на эти мажорные версии.
|
|
47
|
+
- **Окружение:** `bx-rest` ориентирован на браузер. Источники авторизации `cookies`/`localStorage`/`sessid` и `SessionKeyServices` напрямую читают `window`, `document` и `localStorage`. В приложении с серверным рендерингом (Angular Universal, Next.js и т.п.) выполняйте эти участки кода только в браузере (например, под защитой `isPlatformBrowser`/`typeof window !== 'undefined'`), либо используйте источник авторизации, не обращающийся к браузерным глобальным объектам, например `source: () => accessToken` или `source: 'off'`.
|
|
46
48
|
|
|
47
|
-
##
|
|
49
|
+
## Быстрый старт
|
|
48
50
|
|
|
49
|
-
|
|
51
|
+
Один раз настройте URL портала и источник access-токена, затем создайте клиент и подпишитесь на возвращённый RxJS `Observable`. Указывайте полный URL, включая `https://`.
|
|
50
52
|
|
|
51
53
|
```typescript
|
|
52
54
|
import { firstValueFrom } from 'rxjs'
|
|
@@ -79,41 +81,41 @@ const deals = await firstValueFrom(
|
|
|
79
81
|
console.log(deals)
|
|
80
82
|
```
|
|
81
83
|
|
|
82
|
-
|
|
84
|
+
Не хардкодьте и не коммитьте боевой access-токен. Передавайте его из потока авторизации вашего приложения, ответа сервера или защищённой конфигурации времени выполнения.
|
|
83
85
|
|
|
84
|
-
###
|
|
86
|
+
### Режимы результата
|
|
85
87
|
|
|
86
|
-
REST
|
|
88
|
+
REST-вызовы ленивые: запрос начинается, когда на возвращённый `Observable` подписываются или передают его в `firstValueFrom`.
|
|
87
89
|
|
|
88
|
-
|
|
|
90
|
+
| Метод | Результат |
|
|
89
91
|
| --- | --- |
|
|
90
|
-
| `.res(options?)` |
|
|
91
|
-
| `.resAll()` |
|
|
92
|
-
| `.resVanilla()` |
|
|
93
|
-
| `.mapForVanilla()` |
|
|
92
|
+
| `.res(options?)` | Разворачивает ответ Bitrix и применяет настроенный маппер. Для пагинированных методов возвращает текущую страницу. |
|
|
93
|
+
| `.resAll()` | Загружает и объединяет все страницы. Доступен для пагинированных Navvy-хелперов. |
|
|
94
|
+
| `.resVanilla()` | Возвращает сырой ответ Bitrix, включая такие поля, как `result`, `total` и `next`. |
|
|
95
|
+
| `.mapForVanilla()` | Сохраняет исходную обёртку ответа, но применяет маппер к её `result`. |
|
|
94
96
|
|
|
95
|
-
`.res()`
|
|
97
|
+
`.res()` принимает необязательный объект опций:
|
|
96
98
|
|
|
97
|
-
|
|
|
99
|
+
| Опция | По умолчанию | Эффект |
|
|
98
100
|
| --- | --- | --- |
|
|
99
|
-
| `throwOnApiError` | `false` |
|
|
101
|
+
| `throwOnApiError` | `false` | При `true` ошибка API-уровня Bitrix приводит к тому, что возвращённый `Observable` завершается ошибкой `BXRestApiError` вместо резолва в `undefined`. См. [Обработка ошибок](#обработка-ошибок). |
|
|
100
102
|
|
|
101
|
-
##
|
|
103
|
+
## Аутентификация и OAuth2
|
|
102
104
|
|
|
103
|
-
`auth.source`
|
|
105
|
+
`auth.source` определяет, откуда читаются учётные данные. `auth.key` определяет имя параметра запроса, за исключением специального режима учётных данных через куки `OAuth2`.
|
|
104
106
|
|
|
105
|
-
|
|
|
107
|
+
| Сценарий | `auth.source` | `auth.key` | Поведение |
|
|
106
108
|
| --- | --- | --- | --- |
|
|
107
|
-
| Access
|
|
108
|
-
| Access
|
|
109
|
-
| Access
|
|
110
|
-
|
|
|
111
|
-
|
|
|
112
|
-
|
|
|
109
|
+
| Access-токен из состояния приложения | `() => accessToken` | `auth` | Вызывает функцию перед каждым запросом и отправляет её значение в параметре `auth`. Рекомендуется для OAuth2 access-токенов, которыми управляет приложение. |
|
|
110
|
+
| Access-токен в local storage | `localStorage` | `auth` | Читает `localStorage["auth"]` и отправляет его как `auth`. |
|
|
111
|
+
| Access-токен в куке | `cookies` | `auth` | Читает куку `auth` и отправляет её как `auth`. |
|
|
112
|
+
| Встроенная страница Bitrix / локальная сессия | `cookies` | `sessid` | Пробует `window.BX.bitrix_sessid()`, query-параметр `sessid`, `localStorage.sessid`, затем куку `auth`. Отправляет полученное значение как `sessid`. |
|
|
113
|
+
| Входящий вебхук или URL, уже содержащий авторизацию | `off` | Любое значение | Пропускает поиск учётных данных и не добавляет параметр авторизации. |
|
|
114
|
+
| Запрос учётных данных через куки | Любой источник, возвращающий непустое значение | `OAuth2` | Не добавляет полученное значение в параметры запроса и включает `withCredentials` в Axios. Используйте только если портал и политика CORS поддерживают куки с учётными данными. |
|
|
113
115
|
|
|
114
|
-
|
|
116
|
+
Для обычного OAuth2 `access_token` Bitrix используйте `auth.key: 'auth'` и передавайте текущий токен через функцию или `localStorage`. Специальный режим `auth.key: 'OAuth2'` предназначен для куки с учётными данными; сам по себе он не отправляет OAuth access-токен.
|
|
115
117
|
|
|
116
|
-
|
|
118
|
+
Для URL входящего вебхука сохраните полный путь вебхука в `urls.key`, установите `additional_part` в пустую строку и отключите дополнительную авторизацию:
|
|
117
119
|
|
|
118
120
|
```typescript
|
|
119
121
|
BXRestSettings.update({
|
|
@@ -129,18 +131,18 @@ BXRestSettings.update({
|
|
|
129
131
|
})
|
|
130
132
|
```
|
|
131
133
|
|
|
132
|
-
##
|
|
134
|
+
## Обработка ошибок
|
|
133
135
|
|
|
134
|
-
`bx-rest`
|
|
136
|
+
`bx-rest` показывает два разных вида сбоев, и `.res()` реагирует только на один из них.
|
|
135
137
|
|
|
136
|
-
|
|
|
138
|
+
| Сбой | Когда происходит | Как проявляется в `.res()` |
|
|
137
139
|
| --- | --- | --- |
|
|
138
|
-
|
|
|
139
|
-
|
|
|
140
|
+
| Ошибки транспорта / конфигурации — сбой сети, отсутствие авторизации, отсутствие базового URL | До или во время HTTP-вызова | Возвращённый `Observable` завершается ошибкой. Обрабатывайте её через RxJS `catchError` или колбэк `error` у `subscribe()`. |
|
|
141
|
+
| Ошибки API Bitrix — `{ error, error_description }`, например `INSUFFICIENT_SCOPE`, `expired_token` | HTTP-ответ 200, тело которого не является успешным payload'ом | По умолчанию `.res()` резолвится обычным образом со значением `undefined` — **исключение не выбрасывается**. Передайте `{ throwOnApiError: true }`, чтобы вместо этого выбрасывалось `BXRestApiError`. |
|
|
140
142
|
|
|
141
|
-
|
|
143
|
+
Поскольку ошибка уровня Bitrix по умолчанию резолвится как `undefined`, а не как ошибка `Observable`, не полагайтесь только на голый `.res()`, чтобы отличить «нет записей» от «запрос не удался». Есть два варианта.
|
|
142
144
|
|
|
143
|
-
|
|
145
|
+
**Вариант 1 — включить выброс исключения через `.res({ throwOnApiError: true })`.** `Observable` завершается ошибкой `BXRestApiError`, предоставляющей `error` и `error_description`, поэтому её можно обработать вместе с транспортными ошибками в одном колбэке `catchError`/`error`:
|
|
144
146
|
|
|
145
147
|
```typescript
|
|
146
148
|
import { BXRestNavvy, BXRestApiError } from 'bx-rest'
|
|
@@ -163,7 +165,7 @@ bxRest.crm.deal.list({
|
|
|
163
165
|
})
|
|
164
166
|
```
|
|
165
167
|
|
|
166
|
-
|
|
168
|
+
**Вариант 2 — оставить поведение по умолчанию и проверять сырой ответ.** Вызовите `.resVanilla()` и проверьте ответ с помощью экспортируемого type guard `isBXRestAnswerSuccess()`:
|
|
167
169
|
|
|
168
170
|
```typescript
|
|
169
171
|
import { firstValueFrom } from 'rxjs'
|
|
@@ -186,7 +188,7 @@ if (!answer || !isBXRestAnswerSuccess(answer)) {
|
|
|
186
188
|
}
|
|
187
189
|
```
|
|
188
190
|
|
|
189
|
-
|
|
191
|
+
Независимо от `throwOnApiError`, ошибки транспортного уровня всегда всплывают как ошибки `Observable` и могут быть перехвачены обычным способом RxJS:
|
|
190
192
|
|
|
191
193
|
```typescript
|
|
192
194
|
bxRest.crm.deal.list({
|
|
@@ -199,9 +201,9 @@ bxRest.crm.deal.list({
|
|
|
199
201
|
})
|
|
200
202
|
```
|
|
201
203
|
|
|
202
|
-
##
|
|
204
|
+
## Использование в Angular
|
|
203
205
|
|
|
204
|
-
|
|
206
|
+
Зарегистрируйте публичные клиенты и `Navvy`, когда нужно внедрять их в сервисы или компоненты Angular:
|
|
205
207
|
|
|
206
208
|
```typescript
|
|
207
209
|
import { ApplicationConfig, Provider } from '@angular/core'
|
|
@@ -242,7 +244,7 @@ export const appConfig: ApplicationConfig = {
|
|
|
242
244
|
}
|
|
243
245
|
```
|
|
244
246
|
|
|
245
|
-
|
|
247
|
+
Пример компонента:
|
|
246
248
|
|
|
247
249
|
```typescript
|
|
248
250
|
import { Component, inject } from '@angular/core'
|
|
@@ -267,7 +269,7 @@ export class ListComponent {
|
|
|
267
269
|
|
|
268
270
|
## SessionKeyServices
|
|
269
271
|
|
|
270
|
-
`SessionKeyServices`
|
|
272
|
+
`SessionKeyServices` доступен из публичного API и может использоваться, когда нужно проверить текущие данные авторизации перед выполнением REST-запросов.
|
|
271
273
|
|
|
272
274
|
```typescript
|
|
273
275
|
import { BXRestSettings, SessionKeyServices, SessionKeyError } from 'bx-rest'
|
|
@@ -306,7 +308,7 @@ session.getBaseUrl().subscribe((baseUrl) => {
|
|
|
306
308
|
})
|
|
307
309
|
```
|
|
308
310
|
|
|
309
|
-
##
|
|
311
|
+
## Использование в Vue
|
|
310
312
|
|
|
311
313
|
```typescript
|
|
312
314
|
import type { Plugin } from 'vue'
|
|
@@ -349,9 +351,9 @@ app.use(bxRestPlugin)
|
|
|
349
351
|
app.mount('#app')
|
|
350
352
|
```
|
|
351
353
|
|
|
352
|
-
##
|
|
354
|
+
## Использование в React
|
|
353
355
|
|
|
354
|
-
|
|
356
|
+
Создавайте клиент вне компонента и отписывайтесь при размонтировании компонента:
|
|
355
357
|
|
|
356
358
|
```tsx
|
|
357
359
|
import { useEffect, useState } from 'react'
|
|
@@ -379,15 +381,15 @@ export function Deals() {
|
|
|
379
381
|
}
|
|
380
382
|
```
|
|
381
383
|
|
|
382
|
-
##
|
|
384
|
+
## Кастомные REST-методы
|
|
383
385
|
|
|
384
|
-
`Navvy`
|
|
386
|
+
`Navvy` экспортируется из `bx-rest`. В Angular зарегистрируйте показанный выше `NavvyProvider` и внедрите `Navvy` в ваш кастомный API-сервис. URL метода представлен массивом и перед отправкой запроса соединяется точками.
|
|
385
387
|
|
|
386
|
-
|
|
388
|
+
Для регистрации кастомных REST-методов см. [документацию Bitrix24](https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=99&LESSON_ID=7985).
|
|
387
389
|
|
|
388
390
|
### Mapper
|
|
389
391
|
|
|
390
|
-
|
|
392
|
+
Маппер — это обычная функция. Ей не нужно наследоваться от `BXRestMap`.
|
|
391
393
|
|
|
392
394
|
```typescript
|
|
393
395
|
import {
|
|
@@ -407,9 +409,9 @@ export class BXCustomBlogMap {
|
|
|
407
409
|
}
|
|
408
410
|
```
|
|
409
411
|
|
|
410
|
-
###
|
|
412
|
+
### Кастомный метод с `simple()`
|
|
411
413
|
|
|
412
|
-
|
|
414
|
+
Используйте `simple()`, когда метод возвращает один ответ без автоматической пагинации:
|
|
413
415
|
|
|
414
416
|
```typescript
|
|
415
417
|
import { inject, Injectable } from '@angular/core'
|
|
@@ -445,11 +447,11 @@ export class BXRestNavvyCustomApiBlog {
|
|
|
445
447
|
}
|
|
446
448
|
```
|
|
447
449
|
|
|
448
|
-
|
|
450
|
+
Возвращённый хелпер поддерживает `.res()`, `.resVanilla()` и `.mapForVanilla()`.
|
|
449
451
|
|
|
450
|
-
###
|
|
452
|
+
### Пагинированный кастомный метод с `pagNav()`
|
|
451
453
|
|
|
452
|
-
|
|
454
|
+
Используйте `pagNav()`, когда ответ Bitrix содержит массив и стандартные поля пагинации `start`, `next` и `total`. Тип параметра должен поддерживать `start?: number`.
|
|
453
455
|
|
|
454
456
|
```typescript
|
|
455
457
|
import { inject, Injectable } from '@angular/core'
|
|
@@ -489,13 +491,13 @@ export class BXRestNavvyCustomApiBlogList {
|
|
|
489
491
|
}
|
|
490
492
|
```
|
|
491
493
|
|
|
492
|
-
|
|
494
|
+
Возвращённый хелпер дополнительно поддерживает `.resAll()` для загрузки и объединения всех страниц.
|
|
493
495
|
|
|
494
|
-
##
|
|
496
|
+
## Специфичные методы
|
|
495
497
|
|
|
496
498
|
### `tasks.task.list`
|
|
497
499
|
|
|
498
|
-
|
|
500
|
+
Первый generic-аргумент выбирает встроенные поля задачи. Второй добавляет пользовательские поля, специфичные для проекта:
|
|
499
501
|
|
|
500
502
|
```typescript
|
|
501
503
|
import { BXRestNavvy } from 'bx-rest'
|
|
@@ -542,22 +544,22 @@ const tasks$ = bxRest.tasks.task.list<
|
|
|
542
544
|
}).res()
|
|
543
545
|
```
|
|
544
546
|
|
|
545
|
-
##
|
|
547
|
+
## Парсинг дат
|
|
546
548
|
|
|
547
|
-
|
|
549
|
+
Некоторые REST-поля Bitrix24 (в частности `calendar.section.get`, `calendar.event.get` и `crm.calllist.*`) возвращают даты в виде обычных строк, отформатированных согласно собственным настройкам даты/времени портала (Настройки → формат даты и времени), а не в фиксированном формате ISO. Поскольку этот формат — настройка конкретного портала, `bx-rest` не может знать его заранее, поэтому `BXBaseServices.toDate()` (используется этими мапперами внутренне) разрешает неоднозначную строку в три шага, по порядку:
|
|
548
550
|
|
|
549
|
-
1.
|
|
550
|
-
2.
|
|
551
|
-
3.
|
|
551
|
+
1. **Формат, который вы указали.** Если вы (или маппер) передаёте явный `format` (например, `'dd.MM.yyyy HH:mm:ss'`), он проверяется первым, токен за токеном (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss` и их однобуквенные варианты) с буквальными разделителями из строки формата.
|
|
552
|
+
2. **Небольшой список известных форматов Bitrix24** (`'dd.MM.yyyy HH:mm:ss'`, `'yyyy-MM-dd HH:mm:ss'`, `'dd.MM.yyyy'`, `'yyyy-MM-dd'`) — проверяется, если шаг 1 не подошёл, поскольку разные порталы обычно присылают один из этих форматов.
|
|
553
|
+
3. **Позиционная эвристика** как последний вариант — она находит год по его однозначной 4-значной длине (независимо от того, на каком конце даты он стоит), считает средний сегмент месяцем (это верно и для ISO, и для европейского формата даты) и распознаёт любой разделитель (`.`, `-`, `/`, пробел...). Она **не** пытается угадать в единственном действительно неоднозначном случае — чисто числовой порядок `MM/dd` против `dd/MM`, когда оба сегмента ≤ 12, — и проверяет диапазоны значений (месяц 1-12, день 1-31, час/минута/секунда), а не позволяет `Date` молча перевести некорректное значение на следующий месяц/год.
|
|
552
554
|
|
|
553
|
-
|
|
555
|
+
Если вы точно знаете формат вашего портала, передавайте его явно вместо того, чтобы полагаться на автоопределение — он всегда проверяется первым и полностью пропускает шаги 2-3. Мапперы календаря и списка звонков принимают его как единственный необязательный завершающий аргумент `dateTimeFormat`, и он также передаётся через соответствующие методы `BXRestNavvy`. Там, где у маппера есть ещё и поля только с датой (`EXDATE`/`RRULE.UNTIL` у `calendar.event`), их формат выводится из `dateTimeFormat` отбрасыванием `HH:mm:ss` — порядок день/месяц/год всегда одинаков для обоих на конкретном портале, поэтому передавать дополнительно нечего:
|
|
554
556
|
|
|
555
557
|
```typescript
|
|
556
558
|
import { BXRestNavvy } from 'bx-rest'
|
|
557
559
|
|
|
558
560
|
const bxRest = new BXRestNavvy()
|
|
559
561
|
|
|
560
|
-
//
|
|
562
|
+
// Формат даты/времени конкретного портала, например из Настройки → формат даты и времени.
|
|
561
563
|
const dateTimeFormat = 'yyyy-MM-dd HH:mm:ss'
|
|
562
564
|
|
|
563
565
|
bxRest.calendar.event.get({ FROM: '01.01.2026', TO: '31.01.2026' }, dateTimeFormat).res()
|
|
@@ -565,12 +567,12 @@ bxRest.calendar.section.get({}, dateTimeFormat).res()
|
|
|
565
567
|
bxRest.crm.callList.get({ ID: 1 }, dateTimeFormat).res()
|
|
566
568
|
```
|
|
567
569
|
|
|
568
|
-
##
|
|
569
|
-
-
|
|
570
|
-
-
|
|
570
|
+
## Планы на будущее
|
|
571
|
+
- Автоматическое получение токена
|
|
572
|
+
- Мапперы для типов нормализации
|
|
571
573
|
|
|
572
|
-
|
|
574
|
+
Есть предложение по функциональности или нашли баг? Посмотрите [существующие issues](https://github.com/Aricatofuka/bx-rest/issues) или создайте новый.
|
|
573
575
|
|
|
574
|
-
##
|
|
576
|
+
## Лицензия
|
|
575
577
|
|
|
576
|
-
[MIT](https://github.com/Aricatofuka/bx-rest/blob/main/LICENSE) © Aricatofuka
|
|
578
|
+
[MIT](https://github.com/Aricatofuka/bx-rest/blob/main/LICENSE) © Aricatofuka
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bx-rest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "Bitrix24 REST API client and TypeScript SDK for Angular, Vue and browser apps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bitrix",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"url": "https://github.com/Aricatofuka/bx-rest/issues"
|
|
28
28
|
},
|
|
29
29
|
"homepage": "https://github.com/Aricatofuka/bx-rest#readme",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/Aricatofuka/bx-rest.git"
|
|
33
|
+
},
|
|
30
34
|
"dependencies": {
|
|
31
35
|
"axios": "^1.19.0",
|
|
32
36
|
"countries-and-timezones": "^3.7.2",
|
|
@@ -42,6 +46,7 @@
|
|
|
42
46
|
},
|
|
43
47
|
"files": [
|
|
44
48
|
"README.md",
|
|
49
|
+
"README.en.md",
|
|
45
50
|
"LICENSE",
|
|
46
51
|
"*.d.ts",
|
|
47
52
|
"consts",
|