# SC Zabbix API Client

A TypeScript library for consuming the Zabbix JSON-RPC API with support for both token authentication and user/password login.

## Features

- ✅ Authentication via API token
- ✅ Authentication via username/password with session management
- ✅ Full TypeScript support with strong typing
- ✅ ES modules compatible
- ✅ Specific methods for common operations
- ✅ Generic method for custom calls
- ✅ Robust error handling with detailed error types
- ✅ Automatic retry logic with exponential backoff
- ✅ Connection timeout handling and testing
- ✅ Automatic session management for login-based authentication

## Installation

```bash
npm install
```

## Configuration

1. Copy the `.env.example` file to `.env`:

```bash
cp .env.example .env
```

2. Configure your Zabbix credentials in the `.env` file:

```bash
ZABBIX_URL=https://your-zabbix-server.com/api_jsonrpc.php
ZABBIX_TOKEN=your-api-token-here
ZABBIX_TIMEOUT=10000
```

### Configuration Options

The `ZabbixApiConfig` interface supports the following options:

- `url: string` - Zabbix API URL (usually ends with `/api_jsonrpc.php`)
- `token?: string` - Zabbix API token (for token authentication)
- `username?: string` - Username (for session authentication)
- `password?: string` - Password (for session authentication)
- `timeout?: number` - Default timeout in milliseconds (default: 10000)
- `loginTimeout?: number` - Timeout for login operations in milliseconds (default: 15000)
- `retries?: number` - Number of retry attempts for failed requests (default: 3)
- `retryDelay?: number` - Base delay between retries in milliseconds (default: 1000)

## Basic Usage

### Option 1: Using API Token

```typescript
import { SCZabbixApi } from "sc-zabbix-api";

const zabbixApi = new SCZabbixApi({
  url: "https://your-zabbix-server.com/api_jsonrpc.php",
  token: "your-api-token-here",
  timeout: 10000, // optional
});

// Get all hosts
const hosts = await zabbixApi.HostGet();
```

### Option 2: Using Username/Password

```typescript
import { SCZabbixApi } from "sc-zabbix-api";

const zabbixApi = new SCZabbixApi({
  url: "https://your-zabbix-server.com/api_jsonrpc.php",
  timeout: 10000, // optional
});

// Login with username and password
const loginResponse = await zabbixApi.UserLogin({
  username: "your-username",
  password: "your-password",
  userData: true, // optional: retrieve user data
});

console.log("Session ID:", loginResponse.result.sessionid);

// Now you can make API calls
const hosts = await zabbixApi.HostGet();

// Don't forget to logout when done
await zabbixApi.UserLogout();
```

### Error Handling

The library provides enhanced error handling with specific error types:

```typescript
import { SCZabbixApi, ZabbixConnectionError } from "sc-zabbix-api";

try {
  const api = new SCZabbixApi({
    url: "https://your-zabbix-server.com/api_jsonrpc.php",
    token: "your-token",
    timeout: 5000,
    retries: 3,
  });

  // Test connectivity
  const connectionTest = await api.testConnection();
  if (!connectionTest.success) {
    console.error(`Connection failed: ${connectionTest.error}`);
    return;
  }

  const hosts = await api.HostGet();
} catch (error) {
  if (error instanceof Error && "type" in error) {
    const connError = error as ZabbixConnectionError;

    switch (connError.type) {
      case "TIMEOUT":
        console.error("Request timed out - try increasing timeout");
        break;
      case "CONNECTION_REFUSED":
        console.error(
          "Server refused connection - check URL and server status"
        );
        break;
      case "NETWORK_ERROR":
        console.error("Network error - check connectivity");
        break;
      case "AUTH_ERROR":
        console.error("Authentication failed - check credentials");
        break;
    }
  }
}
```

### Example: Get Hosts with Parameters

```typescript
// Get hosts with specific parameters
const hosts = await zabbixApi.HostGet({
  output: ["hostid", "host", "name", "status"],
  filter: {
    status: [0], // Only enabled hosts
  },
  selectInterfaces: ["ip", "port", "type"],
  limit: 100,
});
const items = await zabbixApi.getItems("12345");

// Generic call for any API method
const result = await zabbixApi.call("hostgroup.get", {
  output: ["groupid", "name"],
});
```

## API

### Constructor

```typescript
new SCZabbixApi(config: ZabbixApiConfig)
```

**ZabbixApiConfig:**

- `url: string` - Zabbix API URL (usually ends with `/api_jsonrpc.php`)
- `token?: string` - Zabbix API token (for token authentication)
- `username?: string` - Username (for session authentication)
- `password?: string` - Password (for session authentication)
- `timeout?: number` - Default timeout in milliseconds (default: 10000)
- `loginTimeout?: number` - Timeout for login operations in milliseconds (default: 15000)
- `retries?: number` - Number of retry attempts for failed requests (default: 3)
- `retryDelay?: number` - Base delay between retries in milliseconds (default: 1000)

### Methods

#### Connection Testing

- `testConnection()` - Test connectivity to Zabbix server and return latency information

#### Authentication

- `UserLogin(params)` - Authenticate with username and password
- `UserCheckAuthentication(params?)` - Check if current session/token is valid
- `UserLogout()` - Logout and invalidate current session

#### Information

- `ApiinfoVersion()` - Get Zabbix API version

#### Hosts

- `HostGet(params?)` - Retrieve hosts

#### Items

- `ItemGet(params?)` - Retrieve items
- `ItemCreate(params)` - Create new items
- `ItemUpdate(params)` - Update existing items
- `ItemDelete(itemIds)` - Delete items by ID

#### getHosts(): Promise<Host[]>

Returns all Zabbix hosts.

**Returns:** Array of `Host` objects with `hostid` and `host`.

#### getItems(hostId: string): Promise<Item[]>

Returns all items from a specific host.

**Parameters:**

- `hostId: string` - Host ID

**Returns:** Array of `Item` objects with `itemid`, `name`, `key_` and `lastvalue`.

#### call<T, P>(method: string, params: P): Promise<T>

Generic method for custom calls to the Zabbix API.

**Parameters:**

- `method: string` - API method name (e.g., 'host.get', 'item.get')
- `params: P` - Parameters for the method

**Returns:** Typed result as specified.

## Types

### Host

```typescript
interface Host {
  hostid: string;
  host: string;
}
```

### Item

```typescript
interface Item {
  itemid: string;
  name: string;
  key_: string;
  lastvalue: string;
}
```

## How to get an API token

1. Access your Zabbix instance
2. Go to **Administration** → **General** → **API tokens**
3. Click **Create API token**
4. Fill in the name and select the user
5. Configure expiration (if needed)
6. Click **Add**
7. Copy the generated token

## Tests

Run tests using Vitest:

```bash
# Run all tests
npm test

# Run tests with visual interface
npm run test:ui

# Run tests once (CI/CD)
npm run test:run

# Run tests with coverage
npm run test:coverage
```

**Important:** Tests make real calls to your Zabbix API. Make sure to configure the `.env` file with your credentials before running tests.

## Build

```bash
npm run build
```

## Development

```bash
npm run dev  # Watch mode
```

## Development Testing

```bash
npm test  # Watch mode for tests
```

## Zabbix API Documentation

For more information about available methods, see the [official Zabbix API documentation](https://www.zabbix.com/documentation/current/en/manual/api/reference).

## License

MIT
