Files
mostovik-backend/ts_client/README.md

193 lines
9.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TypeScript-клиент API организаций Mostovik
Клиент покрывает два endpoint API v2:
- `GET /api/v2/organizations/` — список организаций.
- `GET /api/v2/organizations/{uid}/` — карточка одной организации.
Пакет не имеет runtime-зависимостей и использует `fetch`. В `settings.dev` backend открывает эти endpoint без JWT, в остальных окружениях можно передать `accessToken` или свои headers.
```ts
import { MostovikOrganizationsClient } from "@mostovik/organizations-api-client";
const client = new MostovikOrganizationsClient({
baseUrl: "https://backend.example.com",
accessToken: "<jwt>",
});
const page = await client.listOrganizations({
page: 1,
page_size: 20,
search: "мост",
has_registry: true,
has_industrial: true,
data: ["industrial", "fns_reports"],
});
const item = await client.getOrganization(page.data[0].uid, {
data_sources: ["industrial", "fns_reports"],
});
```
## Методы
### `listOrganizations(params?, options?)`
Вызывает `GET /api/v2/organizations/`.
Возвращает пагинированный ответ:
```ts
{
success: true,
data: Organization[],
errors: null,
meta: {
pagination: {
page: number,
page_size: number,
total_count: number,
total_pages: number,
has_next: boolean,
has_previous: boolean,
},
},
}
```
Важно: backend по умолчанию применяет `has_registry=true` для list endpoint, если параметр `has_registry` не передан. Чтобы получить организации без активного участия в реестрах, передайте `has_registry: false`.
### `getOrganization(uid, params?, options?)`
Вызывает `GET /api/v2/organizations/{uid}/`.
Возвращает сам объект `Organization`, без wrapper `success/data/meta`.
## Параметры списка
| Параметр | Тип | Назначение |
| --- | --- | --- |
| `page` | `number` | Номер страницы пагинации. Backend default: `1`. |
| `page_size` | `number` | Размер страницы. Backend default: `20`, максимум `100`. |
| `search` | `string` | Поиск по наименованию, ИНН, КПП, ОГРН и ОГРИП. |
| `ordering` | `OrganizationOrdering` | Сортировка по `uid`, `name`, `inn`, `kpp`, `ogrn`, `ogrip`; префикс `-` включает обратный порядок, например `-name`. |
| `name` | `string` | Фильтр по части полного наименования организации. |
| `inn` | `string` | Точный фильтр по ИНН. |
| `kpp` | `string` | Точный фильтр по КПП. |
| `ogrn` | `string` | Точный фильтр по ОГРН. |
| `ogrip` | `string` | Точный фильтр по ОГРИП. |
| `registry` | `string` | UUID реестра. Возвращает организации с активным участием в этом реестре. |
| `registry_name` | `string` | Фильтр по части наименования реестра. |
| `has_registry` | `boolean` | Фильтр наличия активного участия в любом реестре. |
| `has_industrial` | `boolean` | Наличие данных источника `industrial`. |
| `has_industrial_products` | `boolean` | Наличие данных источника `industrial_products`. |
| `has_manufactures` | `boolean` | Наличие данных источника `manufactures`. |
| `has_inspections` | `boolean` | Наличие данных источника `inspections`. |
| `has_procurements` | `boolean` | Наличие данных источника `procurements`. |
| `has_procurements_44fz` | `boolean` | Наличие данных источника `procurements_44fz`. |
| `has_procurements_223fz` | `boolean` | Наличие данных источника `procurements_223fz`. |
| `has_contracts` | `boolean` | Наличие данных источника `contracts`. |
| `has_unfair_suppliers` | `boolean` | Наличие данных источника `unfair_suppliers`. |
| `has_fas_goz` | `boolean` | Наличие данных источника `fas_goz`. |
| `has_arbitration` | `boolean` | Наличие данных источника `arbitration`. |
| `has_fedresurs_bankruptcy` | `boolean` | Наличие данных источника `fedresurs_bankruptcy`. |
| `has_fstec` | `boolean` | Наличие данных источника `fstec`. |
| `has_vacancies` | `boolean` | Наличие данных публичного источника API v2 `vacancies`. Внутренний backend source — `trudvsem`. |
| `has_trudvsem` | `boolean` | Deprecated alias backend для `has_vacancies`; оставлен в типах, но новый код должен использовать `has_vacancies`. |
| `has_fns_reports` | `boolean` | Наличие данных источника `fns_reports`. |
| `data` | `OrganizationDataSource \| OrganizationDataSource[]` | Вернуть в блоке `data` только указанные источники. |
| `data_sources` | `OrganizationDataSource \| OrganizationDataSource[]` | Alias для `data`. |
| `exclude_data` | `OrganizationDataSource \| OrganizationDataSource[]` | Исключить указанные источники из блока `data`. |
| `exclude_data_sources` | `OrganizationDataSource \| OrganizationDataSource[]` | Alias для `exclude_data`. |
## Параметры карточки
`getOrganization(uid, params)` принимает path-параметр `uid` и параметры управления блоком `data`:
| Параметр | Тип | Назначение |
| --- | --- | --- |
| `uid` | `string` | UID организации в path: `/api/v2/organizations/{uid}/`. |
| `data` | `OrganizationDataSource \| OrganizationDataSource[]` | Вернуть в блоке `data` только указанные источники. |
| `data_sources` | `OrganizationDataSource \| OrganizationDataSource[]` | Alias для `data`. |
| `exclude_data` | `OrganizationDataSource \| OrganizationDataSource[]` | Исключить указанные источники из блока `data`. |
| `exclude_data_sources` | `OrganizationDataSource \| OrganizationDataSource[]` | Alias для `exclude_data`. |
Backend также принимает CSV-строки для `data`/`exclude_data`, но в клиенте лучше передавать массив: так TypeScript проверит допустимые source keys.
## Источники данных
Допустимые публичные source keys API v2:
- `arbitration`
- `contracts`
- `fas_goz`
- `fedresurs_bankruptcy`
- `fns_reports`
- `fstec`
- `industrial`
- `industrial_products`
- `inspections`
- `manufactures`
- `procurements`
- `procurements_44fz`
- `procurements_223fz`
- `unfair_suppliers`
- `vacancies`
Публичный ключ для Работа России — `vacancies`. Параметры `data=trudvsem` и `data_sources=trudvsem` backend API v2 отклоняет.
## Структуры ответа
`Organization` содержит:
- `uid`, `name`, `normalized_name`, `inn`, `kpp`, `ogrn`, `ogrip`
- `registries` — активные реестры организации: `{ id, name }[]`
- `data_sources` — краткая сводка непустых источников: `{ source, count }[]`
- `data` — объект, где ключи являются source keys, а значения — массивы записей источников
В `types.ts` описаны структуры всех возвращаемых блоков `data`:
- `IndustrialCertificateRecord` для `industrial`
- `IndustrialProductRecord` для `industrial_products`
- `ManufacturerRecord` для `manufactures`
- `InspectionRecord` для `inspections`
- `ProcurementRecord` для `procurements`
- `GenericOrganizationSourceRecord` для `procurements_44fz`, `procurements_223fz`, `contracts`, `unfair_suppliers`, `fas_goz`, `arbitration`, `fedresurs_bankruptcy`, `fstec`, `vacancies`
- `FinancialReportRecord` и `FinancialReportLineValue` для `fns_reports`
Для `GenericOrganizationSourceRecord.payload` используется отдельный тип `GenericSourcePayload`. Это JSON-object, потому что backend сохраняет в этом поле исходный нормализованный документ внешнего generic-источника как `dict`.
## Ошибки
Для HTTP-ответов вне диапазона `2xx` клиент бросает `ApiClientError`:
```ts
import { ApiClientError } from "@mostovik/organizations-api-client";
try {
await client.getOrganization(uid, { data: ["industrial"] });
} catch (error) {
if (error instanceof ApiClientError) {
console.log(error.status);
console.log(error.payload);
}
}
```
`ApiClientError.payload` типизирован как `ApiErrorPayload`:
```ts
{
success: false,
data: null,
errors: Array<{
code: string,
message: string,
details?: JsonObject,
}>,
meta: {
request_id?: string,
} | null,
}
```