Compare commits

..

9 commits

7 changed files with 952 additions and 224 deletions

124
AGENTS.md Normal file
View file

@ -0,0 +1,124 @@
# Zabbix GraphQL API - AI Coding Instructions
## Project Overview
This is a **GraphQL wrapper for Zabbix API** that provides enhanced mass import/export operations, hierarchical host group management, and dynamic schema extensibility. It's built with **Apollo Server**, TypeScript, and uses ES modules throughout.
## Architecture & Key Patterns
### Core Components
- **Entry Point**: `src/index.ts``src/api/start.ts` (Apollo Server setup)
- **Schema Loading**: `src/api/schema.ts` - Dynamic schema merging with extensibility via env vars
- **Resolvers**: `src/api/resolvers.ts` + dynamic hierarchical resolvers via `resolver_helpers.ts`
- **DataSources**: `src/datasources/` - Zabbix API wrappers extending `RESTDataSource`
- **Execution**: `src/execution/` - Complex business logic (importers, deleters)
### Critical Patterns
#### 1. Hierarchical Data Mapping
The core innovation is **automatic mapping** of Zabbix items/tags to GraphQL nested objects:
- Zabbix item key `state.current.values.temperature` → GraphQL `{ state: { current: { values: { temperature } } } }`
- Use `createHierarchicalValueFieldResolver()` in `resolver_helpers.ts`
- Type hints: `json_`, `str_`, `bool_`, `float_` prefixes for value conversion
#### 2. Dynamic Schema Extension (No-Code)
Configure via environment variables:
```bash
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
```
Schema loads dynamically in `schema.ts`, resolvers auto-generated for listed types.
#### 3. Mass Import/Export Pattern
All importers follow hierarchy-first approach:
- **Host Groups**: Process parent groups before children (`getHostGroupHierarchyNames()`)
- **Template Dependencies**: Handle dependent items via deferred creation logic
- **Batch Processing**: Each importer returns array of `Response` objects with success/error details
#### 4. Permission System
Uses Zabbix template groups as permission containers:
- Template groups with prefix `Permissions/` (configurable via `ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX`)
- Queries: `hasPermissions()`, `userPermissions()` in resolvers
- Integration: `ZabbixRequestWithPermissions` wrapper class
## Development Workflow
### Essential Commands
```bash
# Development with hot reload
npm run start
# Production build & run
npm run compile && npm run prod
# GraphQL code generation (watch mode)
npm run codegen
# Testing (with ES modules + mocking setup)
npm test
```
### Environment Setup
Key variables (see README for complete list):
```bash
ZABBIX_BASE_URL=http://zabbix.example.com/zabbix
ZABBIX_AUTH_TOKEN=your-super-admin-token
ZABBIX_EDGE_DEVICE_BASE_GROUP=Roadwork
SCHEMA_PATH=./schema/
```
### Testing Patterns
- **ES Module Mocking**: Uses `jest.mock()` with proper module resolution
- **API Mocking**: Mock `zabbixAPI.executeRequest()` and `zabbixAPI.post()`
- **Permission Bypass**: Mock `ZabbixRequestWithPermissions` for unit tests
- **Integration Tests**: Use real GraphQL queries against mocked Zabbix responses
## File Organization & Conventions
### Schema Files (`schema/`)
- `queries.graphql`, `mutations.graphql` - Main API surface
- `devices.graphql`, `zabbix.graphql` - Core types
- `extensions/` - Custom device types for schema extension
### DataSource Naming
- Pattern: `zabbix-{entity}.ts` (e.g., `zabbix-hosts.ts`, `zabbix-templates.ts`)
- Each exports specialized request classes extending `ZabbixRequest<T>`
- Helper classes: `{Entity}Helper` for common operations
### Generated Code
- `src/schema/generated/graphql.ts` - Auto-generated from schema via GraphQL Code Generator
- Enum values imported from `src/model/model_enum_values.ts`
- **Never edit generated files directly**
### Import Statements
**Always use `.js` extensions** in imports due to ES modules:
```typescript
import {logger} from "../logging/logger.js"; // ✅ Correct
import {logger} from "../logging/logger"; // ❌ Will fail
```
## Debugging & Extensions
### Adding New Device Types
1. Create schema in `schema/extensions/{name}.graphql`
2. Add to `ADDITIONAL_SCHEMAS` env var
3. Add type name to `ADDITIONAL_RESOLVERS` env var
4. Ensure Zabbix items use dot-separated keys matching GraphQL field names
### Common Issues
- **Module Resolution**: Check `.js` extensions in imports
- **Permission Errors**: Verify `ZABBIX_AUTH_TOKEN` has Super Admin rights
- **Schema Changes**: Run `npm run codegen` after modifying `.graphql` files
- **Hierarchical Mapping**: Debug via `createHierarchicalValueFieldResolver()` logs
### Integration Points
- **Zabbix API**: All requests go through `ZabbixAPI` class (extends `RESTDataSource`)
- **Authentication**: Supports both API tokens and session cookies
- **WebSocket**: GraphQL subscriptions enabled via `graphql-ws`
- **Docker**: Multi-stage build with `API_VERSION` build arg
## Testing Strategy
Focus on:
1. **Unit Tests**: Mock Zabbix API responses, test business logic
2. **Integration Tests**: Real GraphQL operations with mocked datasources
3. **Permission Tests**: Verify access control logic
4. **Import/Export Tests**: Test hierarchical processing and error handling

14
NOTES.md Normal file
View file

@ -0,0 +1,14 @@
local auth token: 47d92d4c88ed2ac842357e342e8da9c1f272f4ca0d046d1d6a615a5f7a6b1ab2
alt: 9228fc973883eeb5cab421d5b7ecefeb
## Notizen:
- Get Hosts/Hostgroups funktioniert nicht nativ. Custom Group stört
- TODO: Mutation test
- TODO: Erweiterung test und Anleitung
- Übersicht weche zabbix-api funktionen Abgedeckt sind und welche nicht. gg.f mit einem todo versehen um zu sugerieren, dass es kommen könnte
-
- Devices und Hosts nicht hinreichend erklärt im Kontext allDevices
- Integrated management of user roles and user groups.: aber keiner queries zu Roles und groups, hier explizit auf extension hinweisen

906
README.md
View file

@ -1,300 +1,758 @@
# Zabbix GraphQL API
A modern GraphQL interface for Zabbix, providing enhanced features and easier integration for automation and management.
A GraphQL wrapper for the Zabbix API that provides enhanced mass import/export operations, hierarchical host group management, and dynamic schema extensibility. Built with Apollo Server, TypeScript, and ES modules.
## Purpose
## 🚀 Features
The Zabbix GraphQL API acts as a wrapper and enhancer for the native Zabbix JSON-RPC API. It simplifies complex operations, provides a strongly-typed schema, and adds advanced logic for importing, querying, and managing Zabbix entities like hosts, templates, and user rights.
- **GraphQL Interface**: Modern GraphQL API wrapping Zabbix functionality
- *Reference*: `schema/queries.graphql`, `schema/mutations.graphql`, `src/api/start.ts`
## Key Features & Enhancements
- **Hierarchical Data Mapping**: Automatic mapping of Zabbix items/tags to nested GraphQL objects
- *Reference*: `src/api/resolver_helpers.ts`, `schema/device_value_commons.graphql`, `docs/sample_all_devices_query.graphql`
Compared to the original Zabbix API, this GraphQL API provides several key enhancements:
- **Mass Operations**: Import/export capabilities for hosts, templates, and user rights
- *Reference*: `schema/mutations.graphql` (importHosts, importTemplates, importUserRights, etc.), `docs/sample_import_*.graphql`
* **Mass Import/Export**: Robust support for importing and exporting templates, template groups, hosts, and host groups in bulk.
* **Hierarchical Host Groups**: Automatically handles the creation and resolution of nested host group hierarchies (e.g., `Parent/Child/Leaf`).
* **Template Management**:
* Full support for template items, including complex preprocessing steps and tags.
* **Dependent Item Support**: Intelligent deferred creation logic to handle item dependencies within a template.
* Linked template resolution by name.
* **Advanced Deletion**: Ability to delete templates and template groups not only by ID but also by **name patterns** (supporting Zabbix wildcards like `%`).
* **User Rights & Permissions**:
* Integrated management of user roles and user groups.
* Support for importing/exporting user rights with UUID-based matching for cross-instance consistency.
* On-the-fly permission checks (`hasPermissions`, `userPermissions`).
* **Improved Error Reporting**: Detailed error data from Zabbix is appended to GraphQL error messages, making debugging significantly easier.
* **Strongly Typed Schema**: Leverages GraphQL's type system for clear API documentation and client-side code generation.
* **Dynamic Schema Extensibility**: Easily extend the API with custom schema snippets and dynamic resolvers for specialized device types without modifying the core code.
* **CI/CD Integration**: Includes a ready-to-use Forgejo/Gitea/GitHub Actions workflow for automated building, testing, and deployment.
* **Sample Application (VCR)**: Designed to power the **Virtual Control Room**, a professional cockpit for managing thousands of IoT/Edge devices.
- **Dynamic Schema Extension**: Extend the schema without code changes using environment variables
- *Reference*: `src/api/schema.ts`, `schema/extensions/`, `src/common_utils.ts` (ADDITIONAL_SCHEMAS, ADDITIONAL_RESOLVERS)
## How to Install and Start
- **Permission System**: Role-based access control using Zabbix template groups
- *Reference*: `schema/api_commons.graphql` (Permission enum, PermissionRequest), `src/api/resolvers.ts` (hasPermissions, userPermissions), `docs/sample_import_permissions_template_groups_mutation.graphql`
### Prerequisites
- **Real-time Subscriptions**: WebSocket support for GraphQL subscriptions (infrastructure implemented, but no actual subscriptions defined in schema)
- *Reference*: `src/api/start.ts` (WebSocketServer integration with `graphql-ws`), `AGENTS.md` (mentions WebSocket support), `package.json` (graphql-ws, subscriptions dependencies)
* **Node.js**: Version 18 or higher recommended.
* **Zabbix**: A running Zabbix instance (compatible with Zabbix 6.0+).
- **Type Safety**: Full TypeScript support with generated types
- *Reference*: `codegen.ts`, `src/schema/generated/graphql.ts`, `tsconfig.json`, `package.json` (devDependencies for GraphQL Codegen)
### Installation
## 📋 Prerequisites
1. Clone the repository:
```bash
git clone <repository-url>
cd zabbix-graphql-api
```
Before you begin, ensure you have met the following requirements:
2. Install dependencies:
```bash
npm install
```
- **Node.js** >= 18.x (tested with v21.5.0)
- **NPM** >= 8.x
- **Zabbix Server** with API access
- **Zabbix Super Admin Token** (for full functionality)
### Configuration
## 🛠️ Installation
The API is configured via environment variables. Create a `.env` file or set them in your environment:
### Clone the repository
| Variable | Description | Default |
| :--- | :--- | :--- |
| `ZABBIX_BASE_URL` | URL to your Zabbix API (e.g., `http://zabbix.example.com/zabbix`) | |
| `ZABBIX_AUTH_TOKEN` | Zabbix Super Admin API token for administrative tasks | |
| `ZABBIX_EDGE_DEVICE_BASE_GROUP` | Base host group for devices | `Roadwork` |
| `ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX` | Prefix for template groups used as permissions | `Permissions` |
| `SCHEMA_PATH` | Path to the directory containing `.graphql` schema files | `./schema/` |
| `HOST_GROUP_FILTER_DEFAULT` | Default search pattern for `allHostGroups` query | |
| `HOST_TYPE_FILTER_DEFAULT` | Default value for `tag_hostType` filter in `allHosts` and `allDevices` queries | |
### Starting the API
#### Development Mode
Starts the server with `nodemon` and `tsx` for automatic reloading:
```bash
npm run start
git clone https://github.com/your-repo/zabbix-graphql-api.git
cd zabbix-graphql-api
```
#### Production Mode
Builds the project and runs the compiled code:
### Install dependencies
```bash
npm run prod
npm install
```
The API will be available at `http://localhost:4000/`.
## ⚙️ Configuration
## Running with Docker
### Environment Variables
### Using the Pre-built Image
You can run the API without building it locally by pulling the latest image from the Hilbig IT Forgejo infrastructure:
Create a `.env` file in the project root with the following variables:
```bash
docker pull forgejo.tooling.hilbigit.com/zabbix/zabbix-graphql-api:latest
# Zabbix connection
ZABBIX_BASE_URL=http://your-zabbix-server/zabbix
ZABBIX_AUTH_TOKEN=your-super-admin-token
ZABBIX_AUTH_TOKEN_FOR_REQUESTS=your-super-admin-token
# Optional configuration
ZABBIX_EDGE_DEVICE_BASE_GROUP=Roadwork
ZABBIX_ROADWORK_BASE_GROUP=Roadwork
ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX=Permissions
SCHEMA_PATH=./schema/
# Dynamic schema extension (optional)
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
# Logging
LOG_LEVELS=info
```
Start the container by passing the required environment variables:
### Environment Variable Details
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `ZABBIX_BASE_URL` | URL to your Zabbix server (include `/zabbix` path) | - | Yes |
| `ZABBIX_AUTH_TOKEN` | Zabbix Super Admin API token for administrative operations (full permissions needed for import/export operations) | - | Yes |
| `ZABBIX_AUTH_TOKEN_FOR_REQUESTS` | Token used for automated requests (can be same as ZABBIX_AUTH_TOKEN or a different token with limited permissions for routine operations) | - | Yes* |
| `ZABBIX_EDGE_DEVICE_BASE_GROUP` | Base group for edge devices | - | No |
| `ZABBIX_ROADWORK_BASE_GROUP` | Base group for roadwork devices | - | No |
| `ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX` | Prefix for permission template groups (used to identify permission-related template groups in Zabbix) | `Permissions` | No |
| `SCHEMA_PATH` | Path to schema files | `./schema/` | No |
| `ADDITIONAL_SCHEMAS` | Comma-separated list of additional schema files | - | No |
| `ADDITIONAL_RESOLVERS` | Comma-separated list of resolver types to generate | - | No |
| `LOG_LEVELS` | Log level configuration | - | No |
| `DRY_RUN` | If set, runs in dry run mode without starting the server (exits immediately after initialization, useful for testing configuration) | - | No |
| `HOST_TYPE_FILTER_DEFAULT` | Default filter for host types | - | No |
| `HOST_GROUP_FILTER_DEFAULT` | Default filter for host groups | - | No |
*Note: `ZABBIX_AUTH_TOKEN_FOR_REQUESTS` is required when different from `ZABBIX_AUTH_TOKEN`, otherwise the same token will be used for all operations.
### Authentication Tokens Explanation
The API supports two different authentication tokens for security separation:
- `ZABBIX_AUTH_TOKEN`: Used for administrative operations like import/export, requires Super Admin privileges
- `ZABBIX_AUTH_TOKEN_FOR_REQUESTS`: Used for routine read operations, can have limited permissions
### Edge Device Group Pattern
The `ZABBIX_EDGE_DEVICE_BASE_GROUP` (or `ZABBIX_ROADWORK_BASE_GROUP`) is used to create a regex pattern `FIND_ZABBIX_EDGE_DEVICE_BASE_GROUP_PREFIX` that identifies edge device groups in Zabbix. This pattern follows the format `^(${ZABBIX_EDGE_DEVICE_BASE_GROUP})\/` and is used to filter and process edge device related data.
### Configuration Examples
#### Development Configuration (.env.development)
```bash
docker run -d \
--name zabbix-graphql-api \
-p 4000:4000 \
-e ZABBIX_BASE_URL=http://your-zabbix-instance/zabbix \
-e ZABBIX_AUTH_TOKEN=your-super-admin-token \
forgejo.tooling.hilbigit.com/zabbix/zabbix-graphql-api:latest
```
# Zabbix connection
ZABBIX_BASE_URL=http://localhost:8080/zabbix
ZABBIX_AUTH_TOKEN=your-dev-super-admin-token
ZABBIX_AUTH_TOKEN_FOR_REQUESTS=your-dev-super-admin-token
### Building Locally
# Optional configuration for development
ZABBIX_EDGE_DEVICE_BASE_GROUP=DevEdge
ZABBIX_ROADWORK_BASE_GROUP=DevRoadwork
ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX=Permissions
SCHEMA_PATH=./schema/
LOG_LEVELS=debug
If you prefer to build the image yourself using the provided `Dockerfile`:
1. Build the image (ensure you provide an `API_VERSION`):
```bash
docker build -t zabbix-graphql-api --build-arg API_VERSION=1.0.0 .
```
2. Run the container:
```bash
docker run -d \
--name zabbix-graphql-api \
-p 4000:4000 \
-e ZABBIX_BASE_URL=http://your-zabbix-instance/zabbix \
-e ZABBIX_AUTH_TOKEN=your-super-admin-token \
zabbix-graphql-api
```
## Extending the Schema
The Zabbix GraphQL API is designed to be highly extensible. You can add your own GraphQL schema snippets and have resolvers dynamically created for them.
### Dynamic Resolvers with `createHierarchicalValueFieldResolver`
The function `createHierarchicalValueFieldResolver` (found in `src/api/resolver_helpers.ts`) allows for the automatic creation of resolvers that map Zabbix items or tags to a hierarchical GraphQL structure. It uses field names and Zabbix item keys (dot-separated) to automatically resolve nested objects.
### Zabbix Preconditions for Hierarchical Mapping
In order for the dynamic resolvers to correctly map Zabbix data to your GraphQL schema, the following preconditions must be met in your Zabbix templates:
* **Key Naming**: Zabbix item keys (or tags) must match the GraphQL field names.
* **Dot Separation**: Use a dot (`.`) as a separator to represent nested object structures. For example, a Zabbix item with the key `state.current.values.temperature` will be automatically mapped to the `temperature` field within the nested structure: `state` -> `current` -> `values` -> `temperature`.
* **Type Hinting**: You can guide the type conversion by prepending a type hint and an underscore to the last token of the key:
* `json_`: Parses the value as a JSON object (useful for complex types).
* `str_`: Forces the value to be treated as a string.
* `bool_`: Forces the value to be treated as a boolean.
* `float_`: Forces the value to be treated as a number.
For a complete example of a Zabbix template designed for schema extension, see the [Distance Tracker Import Sample](docs/sample_import_distance_tracker_template.graphql).
### No-Code Extension via Environment Variables
You can extend the schema and add resolvers without writing any TypeScript code by using the following environment variables:
* **`ADDITIONAL_SCHEMAS`**: A comma-separated list of paths to additional `.graphql` files.
* **`ADDITIONAL_RESOLVERS`**: A comma-separated list of GraphQL Type names for which dynamic hierarchical resolvers should be created.
#### Example
Suppose you have custom device definitions in `schema/extensions/`. You can load them and enable dynamic resolution by setting:
```bash
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql,./schema/extensions/location_tracker_commons.graphql
# Dynamic schema extension (optional)
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
```
The API will:
1. Load all provided schema files.
2. For each type listed in `ADDITIONAL_RESOLVERS`, it will automatically create a resolver that maps Zabbix items (e.g., an item with key `state.current.values.temperature`) to the corresponding GraphQL fields.
#### Production Configuration (.env.production)
```bash
# Zabbix connection
ZABBIX_BASE_URL=https://zabbix.company.com/zabbix
ZABBIX_AUTH_TOKEN=your-prod-super-admin-token
ZABBIX_AUTH_TOKEN_FOR_REQUESTS=your-prod-read-only-token
## User Permissions & `hasPermission`
# Production configuration
ZABBIX_EDGE_DEVICE_BASE_GROUP=ProductionEdge
ZABBIX_ROADWORK_BASE_GROUP=ProductionRoadwork
ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX=Permissions
SCHEMA_PATH=./schema/
LOG_LEVELS=info
The Zabbix GraphQL API provides a sophisticated way to manage and check application-level permissions using Zabbix's built-in user group and template group mechanisms.
# Dynamic schema extension for production
ADDITIONAL_SCHEMAS=/app/schema/extensions/display_devices.graphql,/app/schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
### Modeling Permissions with Template Groups
# Performance and operational settings
HOST_TYPE_FILTER_DEFAULT=device
HOST_GROUP_FILTER_DEFAULT=production
```
Permissions can be modeled as **empty template groups** (groups with no templates or hosts attached) organized in a hierarchical structure. By convention, these groups start with a configurable prefix (default: `Permissions/`).
## ▶️ Running the Application
#### Example Hierarchy:
* `Permissions/ConstructionSite`: General access to construction site data.
* `Permissions/Automatism`: Access to automation features.
* `Permissions/Automatism/Status`: Permission to view automation status.
### Development Mode
### Zabbix Preconditions
```bash
# Start with hot reloading
npm run start
```
1. **Template Groups**: Create template groups for each permission you want to manage (e.g., `Permissions/App1/FeatureA`).
2. **User Groups**: In Zabbix, assign these template groups to Zabbix User Groups with specific permission levels (`READ`, `READ_WRITE`, or `DENY`).
3. **Authentication**: The GraphQL API will check the permissions of the authenticated user (via token or session cookie) against these Zabbix assignments.
The GraphQL API will be available at `http://localhost:4000/`
### Using `hasPermission` and `userPermissions`
#### Available Queries and Mutations after start
The API provides two main queries for permission checking:
#### Queries
- `apiVersion` - Returns the API build version
- `zabbixVersion` - Returns the version of the connected Zabbix instance
- `login` - Authenticates with Zabbix and returns an authentication token
- `logout` - Logs out from Zabbix, invalidating the current session
- `allHosts` - Returns all hosts and their items
- `allDevices` - Returns all devices and their items (hosts with deviceType)
- `allHostGroups` - Returns all host groups
- `locations` - Returns all locations used by hosts
- `exportHostValueHistory` - Exports value history for Zabbix items
- `userPermissions` - Returns all user permissions
- `hasPermissions` - Checks if the current user has requested permissions
- `exportUserRights` - Exports user rights (roles and groups)
- `templates` - Returns templates
- `allTemplateGroups` - Returns all template groups
* **`userPermissions`**: Returns a list of all permissions assigned to the current user.
* **`hasPermissions`**: Checks if the user has a specific set of required permissions (e.g., "Does the user have `READ_WRITE` access to `Automatism/Status`?").
#### Mutations
- `createHost` - Creates a single host in Zabbix
- `importHostGroups` - Mass import Zabbix host groups
- `importHosts` - Mass import hosts and assign them to host groups
- `importUserRights` - Import user rights (roles and groups) into Zabbix
- `importTemplateGroups` - Mass import template groups
- `importTemplates` - Mass import templates
- `deleteTemplates` - Delete templates by their IDs or by a name pattern
- `deleteTemplateGroups` - Delete template groups by their IDs or by a name pattern
This allows for fine-grained access control in your frontend or external applications, using Zabbix as the central authorization authority.
### Production Build
For a complete example of how to import these permission groups, see the [Permissions Template Groups Import Sample](docs/sample_import_permissions_template_groups_mutation.graphql).
```bash
# Compile TypeScript
npm run compile
## Host Classification & Filtering
# Run production build
npm run prod
```
The API leverages Zabbix tags to classify hosts and devices, enabling efficient filtering and multi-tenancy support.
### Available Scripts
### The `hostType` Tag
| Script | Description |
|--------|-------------|
| `npm run start` | Start development server with hot reload |
| `npm run compile` | Compile TypeScript to JavaScript |
| `npm run prod` | Run production build |
| `npm run test` | Run tests |
| `npm run codegen` | Generate TypeScript types from GraphQL schema |
| `npm run nodemon` | Alternative development runner |
The `hostType` tag is used to categorize hosts and templates. This allows the API to provide default filters for specific application domains or device categories.
## 🐳 Docker Deployment
#### How to set the Host Type in Zabbix:
### Using Pre-built Images
To classify a host or a template, simply add a tag in the Zabbix UI or via the API:
* **Tag Name**: `hostType`
* **Tag Value**: A string representing the category (e.g., `Roadwork/Devices`, `SmartCity/Sensors`).
The application can be deployed using Docker:
This tag can be defined:
1. **Directly on the Host**: Specific to that individual device.
2. **On a Template**: All hosts linked to this template will inherit the classification.
```bash
# Build the image
docker build -t zabbix-graphql-api .
### Default Filtering with `HOST_TYPE_FILTER_DEFAULT`
# Run the container
docker run -d \
--name zabbix-graphql \
-p 4000:4000 \
-e ZABBIX_BASE_URL=http://your-zabbix-server/zabbix \
-e ZABBIX_AUTH_TOKEN=your-super-admin-token \
zabbix-graphql-api
```
By configuring the `HOST_TYPE_FILTER_DEFAULT` environment variable, you can set a global default for the `allHosts` and `allDevices` queries.
### Building Your Own Image
* If `HOST_TYPE_FILTER_DEFAULT=Roadwork/Devices` is set, a query like `allHosts { host }` will only return hosts that have the `hostType` tag set to `Roadwork/Devices`.
* This default can always be overridden in the GraphQL query by explicitly passing the `tag_hostType` argument.
```bash
# Build with custom API version
docker build --build-arg API_VERSION=v1.0.0 -t zabbix-graphql-api .
### Search Filtering with `HOST_GROUP_FILTER_DEFAULT`
# Run with environment file
docker run -d \
--name zabbix-graphql \
-p 4000:4000 \
--env-file .env \
zabbix-graphql-api
```
The `HOST_GROUP_FILTER_DEFAULT` variable provides a default search pattern for the `allHostGroups` query. This is particularly useful for restricting the visible host group hierarchy to a specific subtree by default.
## 🔐 Roles and Permissions Extension
#### Overriding the Default Filter
The API implements a permission system using Zabbix template groups:
The default filter can be overridden by explicitly providing the `search_name` argument in the `allHostGroups` query. When `search_name` is present, the environment variable is ignored.
### Permission Template Groups
#### Using Wildcards
- Template groups with prefix `Permissions/` (configurable via `ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX`) are used for permissions
- Users gain permissions by being assigned to user groups that have access to these permission template groups
The `search_name` parameter supports the `*` wildcard (enabled via the Zabbix API's `searchWildcardsEnabled` feature). This allows you to search for all subgroups within a specific path.
### Available Permissions
**Example**: To find all subgroups of `Roadwork/Devices/`, use the following query:
The system supports three permission levels defined in `schema/api_commons.graphql`:
- `DENY`: Explicitly denies access (supersedes other permissions)
- `READ`: Allows viewing/reading access
- `READ_WRITE`: Allows both reading and writing (implies READ permission)
### Permission Object Names
Permission object names map to Zabbix template group paths: `Permissions/{objectName}`
### GraphQL Permission Queries
```graphql
query {
allHostGroups(search_name: "Roadwork/Devices/*") {
groupid
name
# Check if current user has specific permissions
query HasPermissions {
hasPermissions(permissions: [
{ objectName: "hosts", permission: READ },
{ objectName: "templates", permission: READ_WRITE }
])
}
# Get all user permissions
query GetUserPermissions {
userPermissions(objectNames: ["hosts", "templates"])
}
```
### Setting Up Permissions
1. Create template groups with the prefix `Permissions/` (e.g., `Permissions/hosts`, `Permissions/templates`)
2. Assign these template groups to user groups in Zabbix with appropriate permission levels
3. Users in those user groups will inherit the permissions
### Detailed Permission Usage Examples
For comprehensive examples of permission usage patterns, see `schema/api_commons.graphql` which contains detailed documentation in the `PermissionRequest` input type comments, including real-world examples of how to model permissions for buttons, status controls, and application features.
See also `docs/sample_import_permissions_template_groups_mutation.graphql` for examples of importing permission template groups.
## 📊 Schema and Schema Extension
### Main Schema Structure
The GraphQL schema is located in the `schema/` directory and consists of:
- `queries.graphql` - Query definitions (see detailed documentation in file comments)
- `mutations.graphql` - Mutation definitions (see detailed documentation in file comments)
- `devices.graphql` - Device-related types (see detailed documentation in file comments)
- `zabbix.graphql` - Zabbix-specific types (see detailed documentation in file comments)
- `device_value_commons.graphql` - Common value types (see detailed documentation in file comments)
- `api_commons.graphql` - Common API types and permission system (see detailed documentation in file comments)
- `extensions/` - Custom device type extensions
For comprehensive understanding of each operation, read the detailed comments in the respective schema files.
### Zabbix to GraphQL Mapping
The API maps Zabbix entities to GraphQL types as follows:
| Zabbix Entity | GraphQL Type | Description |
|---------------|--------------|-------------|
| Host | `Host` / `Device` | Represents a Zabbix host; `Device` is a specialized `Host` with a `deviceType` tag |
| Host Group | `HostGroup` | Represents a Zabbix host group |
| Template | `Template` | Represents a Zabbix template |
| Template Group | `HostGroup` | Represents a Zabbix template group |
| Item | Nested fields in `Device` | Zabbix items become nested fields in the device based on their key names |
| Tag | `Tag` | Represents a Zabbix tag associated with a host or template |
| Inventory | `Location` | Host inventory information maps to location data |
### Zabbix Entity Relationships
- **Host Groups**: Organize hosts and templates hierarchically; represented as `HostGroup` objects in GraphQL
- **Templates**: Contain items and other configuration that can be applied to hosts; linked via template groups
- **Items**: Individual metrics collected from hosts; automatically mapped to nested GraphQL fields based on their key names
- **Tags**: Metadata associated with hosts/templates; used for classification and filtering
### Location Type Usage
The `Location` type represents geographical information from Zabbix host inventory:
- **Fields**: Includes `name`, `location_lat`, `location_lon`, and other inventory attributes
- **Usage**: Available through the `locations` query and as part of host/device objects
- **Access**: Retrieved via the `getLocations` method in the Zabbix API datasource
### Dynamic Schema Extension
Extend the schema without code changes using environment variables:
```bash
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
```
This enables runtime schema extension for custom device types without modifying the core code.
### Sample Operations
For practical examples of schema usage, see the sample files in the `docs/` directory:
- `docs/sample_all_devices_query.graphql` - Example of querying all devices
- `docs/sample_import_templates_mutation.graphql` - Example of importing templates
- `docs/sample_import_host_groups_mutation.graphql` - Example of importing host groups
## 🗂️ Hierarchical Data Mapping
The API automatically maps Zabbix items to nested GraphQL objects using the `createHierarchicalValueFieldResolver` function:
- Zabbix item key `state.current.values.temperature` → GraphQL `{ state: { current: { values: { temperature } } } }`
- Type hints: `json_`, `str_`, `bool_`, `float_` prefixes for value conversion
- Automatic resolution of hierarchical structures from flat Zabbix item keys
The `createHierarchicalValueFieldResolver` function (found in `src/api/resolver_helpers.ts`) dynamically creates resolvers that map Zabbix items or tags to hierarchical GraphQL structures. It uses field names and Zabbix item keys (dot-separated) to automatically resolve nested objects, eliminating the need for manual resolver definitions for each hierarchical field.
For detailed information about the mapping mechanism and type hinting, see the comments in `schema/device_value_commons.graphql` and `src/api/resolver_helpers.ts`.
See `docs/sample_all_devices_query.graphql` for examples of how hierarchical data appears in query results.
## 🏷️ Zabbix Tags Usage
Zabbix tags are used for:
- Device classification (`deviceType` tag)
- Host categorization (`hostType` tag)
- Custom metadata storage
- Permission assignment through template groups
For detailed information about tag usage and available tag types, see the comments in `schema/devices.graphql` and `schema/zabbix.graphql`.
See `docs/sample_all_hosts_query.graphql` and `docs/sample_all_devices_query.graphql` for examples of how tags appear in query results.
## 🧪 Testing
Run the test suite:
```bash
npm test
```
The testing strategy includes:
- Unit tests with mocked Zabbix API responses
- Integration tests with real GraphQL operations
- Permission system validation
- Import/export functionality testing
## 📖 Detailed Documentation Through Comments
This project uses extensive inline documentation in the form of comments within the GraphQL schema files and documentation samples. For the most comprehensive understanding of the API, its capabilities, and usage patterns, read the detailed comments in:
- `schema/queries.graphql` - Complete documentation of all query operations
- `schema/mutations.graphql` - Complete documentation of all mutation operations with usage examples
- `schema/api_commons.graphql` - Detailed explanation of the permission system with real-world usage examples
- `docs/*.graphql` - Practical examples of all operations with sample variables and expected outcomes
The comments in these files contain real-world usage examples, implementation notes, and detailed explanations that go beyond what's covered in this README.
## 📖 Example: Extending Schema with Distance Tracker Device
### Zabbix-Side Configuration
Before extending the schema, you need to configure Zabbix appropriately:
#### 0. Template Group configuration
- Create a template group `Templates/Roadwork/Devices`
#### 1. Host Configuration in Zabbix
- Create a host in Zabbix with the tag `deviceType` set to `distance-tracker`
- Add items to the host with hierarchical keys that match your GraphQL fields:
- `distance.current` (for the `distance` field)
- `battery.level` (for the `batteryLevel` field)
- `status.lastSeen` (for the `lastSeen` field)
- `location.latitude` and `location.longitude` (for the `location` object)
#### 2. Item Key Naming Convention
The API automatically maps dotted item keys to nested GraphQL objects:
- Zabbix item key `distance.current` → GraphQL `{ distance }`
- Zabbix item key `battery.level` → GraphQL `{ batteryLevel }`
- Zabbix item key `location.latitude` → GraphQL `{ location: { location_lat } }`
### Schema Extension Steps
#### 1. Create Schema Extension
Create `schema/extensions/distance_tracker_device.graphql`:
```graphql
type DistanceTrackerDevice {
id: String
name: String
location: Location
distance: Float
batteryLevel: Float
lastSeen: DateTime
}
```
#### 2. Configure Environment Variables
```bash
ADDITIONAL_SCHEMAS=./schema/extensions/distance_tracker_device.graphql
ADDITIONAL_RESOLVERS=DistanceTrackerDevice
```
#### 3. Import Template via GraphQL Mutation
Instead of manually creating items in Zabbix, you can import a complete template using the GraphQL API:
```graphql
mutation ImportDistanceTrackerTemplate($templates: [CreateTemplate!]!) {
importTemplates(templates: $templates) {
host
templateid
message
error {
message
code
data
}
}
}
```
## Sample Application: Virtual Control Room (VCR)
The **Virtual Control Room (VCR)** is a professional cockpit and control center application designed for monitoring and managing large-scale deployments of IoT and Edge devices, such as traffic management systems, roadwork safety equipment, and environmental sensors.
### How VCR uses the GraphQL API:
* **Unified Cockpit**: VCR utilizes the API's **hierarchical mapping** to provide a unified view of diverse device types. It maps Zabbix items and tags directly to structured GraphQL objects (e.g., `operational` telemetry and `current` business state).
* **Dynamic Authorization**: The `hasPermissions` query is used to implement a **Dynamic UI**. Buttons, controls, and status indicators are shown or enabled only if the user has the required `READ` or `READ_WRITE` permissions for that specific object.
* **Mass Provisioning**: VCR leverages the **mass import** capabilities to provision thousands of devices and templates in a single operation, significantly reducing manual configuration effort in Zabbix.
* **Data Visualization**: It uses the `exportHostValueHistory` endpoint to power dashboards showing historical trends, such as traffic density, battery levels, or sensor readings over time.
For more detailed information about the VCR product, please refer to the technical presentation:
[VCR - Technical product information](docs/VCR%20-%20Technical%20product%20information.pdf)
## Sample Environment File
Below is a complete example of a `.env` file showing all available configuration options:
```env
# Zabbix Connection
ZABBIX_BASE_URL=http://your-zabbix-instance/zabbix
ZABBIX_AUTH_TOKEN=your-super-admin-token-here
# General Configuration
ZABBIX_EDGE_DEVICE_BASE_GROUP=Roadwork
API_VERSION=1.0.0
SCHEMA_PATH=./schema/
HOST_GROUP_FILTER_DEFAULT=Roadwork/Devices/*
HOST_TYPE_FILTER_DEFAULT=Roadwork/Devices
# Schema Extensions (No-Code)
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql,./schema/extensions/location_tracker_commons.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
# Logging
# LOG_LEVEL=debug
Variables:
```json
{
"templates": [
{
"host": "DISTANCE_TRACKER",
"name": "Distance Tracker Device Template",
"groupNames": ["Templates/Roadwork/Devices"],
"tags": [
{ "tag": "deviceType", "value": "DistanceTrackerDevice" }
],
"items": [
{
"name": "Distance Current Value",
"type": 0,
"key": "distance.current",
"value_type": 0,
"history": "7d",
"units": "m"
},
{
"name": "Battery Level",
"type": 0,
"key": "battery.level",
"value_type": 0,
"history": "7d",
"units": "%"
},
{
"name": "Last Seen Timestamp",
"type": 0,
"key": "status.lastSeen",
"value_type": 4,
"history": "30d"
},
{
"name": "Location Latitude",
"type": 0,
"key": "location.latitude",
"value_type": 0,
"history": "30d",
"units": "deg"
},
{
"name": "Location Longitude",
"type": 0,
"key": "location.longitude",
"value_type": 0,
"history": "30d",
"units": "deg"
}
]
}
]
}
```
## Usage Samples
This creates a template in Zabbix with all the required items that map to your GraphQL fields.
The `docs` directory contains several sample GraphQL queries and mutations to help you get started:
#### 4. Link Hosts to the Template
* **Hosts**:
* [Query All Hosts](docs/sample_all_hosts_query.graphql)
* [Import Hosts](docs/sample_import_hosts_mutation.graphql)
* **Templates**:
* [Query Templates](docs/sample_templates_query.graphql)
* [Import Templates](docs/sample_import_templates_mutation.graphql)
* [Import Distance Tracker Template](docs/sample_import_distance_tracker_template.graphql) (Schema Extension Example)
* [Delete Templates](docs/sample_delete_templates_mutation.graphql)
* **Template Groups**:
* [Import Host Template Groups](docs/sample_import_host_template_groups_mutation.graphql)
* [Import Permissions Template Groups](docs/sample_import_permissions_template_groups_mutation.graphql)
* [Delete Template Groups](docs/sample_delete_template_groups_mutation.graphql)
* **User Rights**:
* [Export User Rights](docs/sample_export_user_rights_query.graphql)
* [Import User Rights](docs/sample_import_user_rights_mutation.graphql)
After importing the template, link your hosts to it in Zabbix or via the importHosts mutation:
## License
```graphql
mutation ImportHosts($hosts: [CreateHost!]!) {
importHosts(hosts: $hosts) {
deviceKey
hostid
message
error {
message
code
data
}
}
}
```
This project is licensed under the **GNU Affero General Public License v3.0**. See the [LICENSE](LICENSE) file for details.
Variables:
```json
{
"hosts": [
{
"deviceKey": "DistanceTracker001",
"name": "Distance Tracker 001",
"deviceType": "distance-tracker",
"groupNames": ["Roadwork/Devices"],
"templateids": [12345] // Use the templateid returned from importTemplates
}
]
}
```
#### 5. Use in Queries
Once the template and host are set up in Zabbix, query the data via GraphQL:
```graphql
query GetDistanceTrackers {
allDevices(tag_deviceType: ["distance-tracker"]) {
... on DistanceTrackerDevice {
id
name
location {
name
location_lat
location_lon
}
distance
batteryLevel
lastSeen
}
}
}
```
#### 6. Expected Response Structure
Based on the Zabbix configuration above, the API will return:
```json
{
"data": {
"allDevices": [
{
"id": "12345",
"name": "Distance Tracker 001",
"location": {
"name": "Main Office",
"location_lat": "37.7749",
"location_lon": "-122.4194"
},
"distance": 42.5,
"batteryLevel": 87.2,
"lastSeen": "2023-10-15T10:30:00Z"
}
]
}
}
```
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## 🏗️ Architecture
The Zabbix GraphQL API follows a layered architecture pattern with clear separation of concerns:
![Architecture Diagram](docs/arch-diagram.svg)
<details>
```PlantUML
@startuml
title Zabbix GraphQL API - Simplified Data Flow
[GraphQL Client] as client
[Apollo Server\n(Entry Point)] as server
[Schema Loader\nDynamic Merging] as schema
[Resolvers\nHierarchical] as resolvers
[Data Sources\nZabbix API Wrappers] as datasources
[Zabbix Server] as zabbix
[Execution Layer\nBusiness Logic] as execution
client -> server : "Query/Mutation"
server -> schema : "Resolve Schema"
schema -> resolvers : "Route to Resolver"
resolvers -> datasources : "Fetch Data"
datasources -> zabbix : "API Call"
zabbix -> datasources : "Response"
datasources -> resolvers : "Process"
resolvers -> server : "Format"
server -> client : "Result"
resolvers --> execution : "Complex Operations"
execution --> datasources : "Use DataSources"
@enduml
```
</details>
### Core Components
- **Entry Point**: `src/index.ts``src/api/start.ts` (Apollo Server setup)
- **Schema Loading**: `src/api/schema.ts` - Dynamic schema merging with extensibility via environment variables
- **Resolvers**: `src/api/resolvers.ts` + dynamic hierarchical resolvers via `resolver_helpers.ts`
- **DataSources**: `src/datasources/` - Zabbix API wrappers extending `RESTDataSource`
- **Execution**: `src/execution/` - Complex business logic (importers, deleters)
### Data Flow
1. **Client Request**: GraphQL queries/mutations arrive at the Apollo Server
2. **Schema Resolution**: Schema loader merges base schema with additional schemas (if configured)
3. **Resolver Execution**: Resolvers handle the request, using data sources to communicate with Zabbix
4. **Zabbix Communication**: Data sources make API calls to the Zabbix server
5. **Response Processing**: Results are processed and returned to the client
### DataSources Structure
The `src/datasources/` directory contains specialized Zabbix API wrappers:
- `zabbix-api.ts`: Main Zabbix API class extending `RESTDataSource`, handles authentication and communication
- `zabbix-{entity}.ts`: Specialized request classes for specific Zabbix entities (e.g., hosts, templates, etc.)
- Each DataSource follows the pattern of extending `ZabbixRequest<T>` for type-safe API calls
### Key Architectural Patterns
#### 1. Hierarchical Data Mapping
Automatic mapping of Zabbix items/tags to GraphQL nested objects:
- Zabbix item key `state.current.values.temperature` → GraphQL `{ state: { current: { values: { temperature } } } }`
- Implemented via `createHierarchicalValueFieldResolver()` in `resolver_helpers.ts`
- Type hints: `json_`, `str_`, `bool_`, `float_` prefixes for value conversion
#### 2. Dynamic Schema Extension (No-Code)
Configure via environment variables:
```bash
ADDITIONAL_SCHEMAS=./schema/extensions/display_devices.graphql,./schema/extensions/location_tracker_devices.graphql
ADDITIONAL_RESOLVERS=SinglePanelDevice,FourPanelDevice,DistanceTrackerDevice
```
#### 3. Mass Import/Export Pattern
All importers follow hierarchy-first approach:
- **Host Groups**: Process parent groups before children (`getHostGroupHierarchyNames()`)
- **Template Dependencies**: Handle dependent items via deferred creation logic
- **Batch Processing**: Each importer returns array of `Response` objects with success/error details
#### 4. Permission System
Uses Zabbix template groups as permission containers:
- Template groups with prefix `Permissions/` (configurable via `ZABBIX_PERMISSION_TEMPLATE_GROUP_NAME_PREFIX`)
- Queries: `hasPermissions()`, `userPermissions()` in resolvers
- Integration: `ZabbixRequestWithPermissions` wrapper class
## 📄 License
This project is licensed under the AGPL-3.0 License - see the [LICENSE](LICENSE) file for details.
## 📚 Schema and Documentation
### Schema Files as Documentation
The schema files in the `schema/` directory serve as both API definition and documentation. Each type, field, and operation includes detailed comments explaining usage, parameters, and examples. For comprehensive understanding of the API, read the comments in:
- `schema/queries.graphql` - Query operations with detailed parameter descriptions
- `schema/mutations.graphql` - Mutation operations with input type documentation
- `schema/api_commons.graphql` - Common types and permission system documentation
- `schema/devices.graphql` - Device-related types and hierarchies
- `schema/zabbix.graphql` - Zabbix-specific mappings and types
### Documentation Files
The `docs/` directory contains sample GraphQL queries and mutations that demonstrate how to use the API:
- `sample_all_*.graphql` - Sample queries for retrieving hosts, devices, templates, and groups
- `sample_import_*.graphql` - Sample mutations for importing various Zabbix entities
- `sample_delete_*.graphql` - Sample mutations for deleting templates and template groups
- `sample_export_*.graphql` - Sample queries for exporting user rights and other data
- `VCR - Technical product information.pdf` - Technical documentation for specific implementations
Of particular interest:
- `sample_import_distance_tracker_template.graphql` - Complete example of importing a template for distance tracker devices
- `sample_import_user_rights_mutation.graphql` - Example of importing user permissions
- `sample_import_permissions_template_groups_mutation.graphql` - Example of importing permission template groups
### Reading Comments for Detailed Documentation
For detailed documentation with usage examples and implementation notes, read the comments in the schema and documentation files. The project creator has embedded extensive documentation as comments in the GraphQL schema files, which provide real-world usage examples and implementation guidance that complement this README.
## 🆘 Support
For support, please open an issue in the GitHub repository.
## 🔄 API Version
Current API version: ${API_VERSION:-"Not set"}
The API version is automatically set during the Docker build process based on the Git tag or commit hash. During CI/CD deployment (as defined in `.forgejo/workflows/deploy-docker.yaml`), the API_VERSION is determined using `git describe --tags --always`, which creates a version identifier based on the most recent Git tag and the number of commits since that tag. This version information is then embedded into the Docker image as a build argument and becomes accessible through the API_VERSION environment variable at runtime.
### Zabbix Version Compatibility
This API is designed to work with Zabbix 7.4, which is the version it runs productively with. The API wraps the Zabbix 7.4 API and has been tested extensively with this version. While it may work with other Zabbix versions, 7.4 is the officially supported and tested version.

BIN
docs/arch-diagram.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

1
docs/arch-diagram.svg Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,74 @@
# README Evaluation Result
## Executive Summary
The README.md file provides a comprehensive overview of the Zabbix GraphQL API project with good coverage of features, installation, configuration, and usage examples. The document has been recently enhanced with codebase references and detailed explanations of key features.
## Strengths
- Comprehensive coverage of all major features
- Good separation of sections with clear headings
- Detailed environment variable configuration
- Well-structured example for schema extension
- Proper inclusion of Docker deployment instructions
- References to schema and documentation files
- Clear explanation of the permission system
- Good balance between high-level concepts and technical details
## Areas of Concern
### 1. Missing Information
- No mention of the `DRY_RUN` environment variable functionality
- Missing information about the `HOST_TYPE_FILTER_DEFAULT` and `HOST_GROUP_FILTER_DEFAULT` configuration options
- No explanation of the difference between `ZABBIX_AUTH_TOKEN` and `ZABBIX_AUTH_TOKEN_FOR_REQUESTS`
- Missing details about the `FIND_ZABBIX_EDGE_DEVICE_BASE_GROUP_PREFIX` regex pattern
### 2. Incomplete Information
- The "Real-time Subscriptions" feature claims WebSocket support but no actual subscription operations are defined in the schema
- The API version placeholder `${API_VERSION:-"Not set"}` is not properly populated
- No mention of the generated GraphQL types in `src/schema/generated/graphql.ts`
- Missing information about the test structure and how to run individual tests
### 3. Potential Inaccuracies
- The README mentions that the API is published publicly, but the license is AGPL-3.0-only which has specific distribution requirements
- The Docker example uses `your-zabbix-server` placeholder but doesn't explain how to determine the correct URL format
- The example GraphQL queries might not match the exact schema definitions
### 4. Schema Consistency Issues
- The schema contains many types and operations not mentioned in the README
- Some schema types like `Location` are referenced but not explained
- The relationship between Zabbix entities and GraphQL types could be clearer
### 5. Documentation Completeness
- The AGENTS.md file contains important architectural information not reflected in the README
- The codegen.ts file configuration is not explained
- The relationship between different DataSource files is not clear from the README
## Technical Verification
### Features Verification
- ✅ GraphQL Interface: Confirmed in schema files and start.ts
- ✅ Hierarchical Data Mapping: Confirmed in resolver_helpers.ts
- ✅ Mass Operations: Confirmed in mutations.graphql
- ✅ Dynamic Schema Extension: Confirmed in schema.ts
- ✅ Permission System: Confirmed in api_commons.graphql
- ⚠️ Real-time Subscriptions: Infrastructure exists but no actual subscriptions defined
- ✅ Type Safety: Confirmed with codegen and generated types
### Configuration Verification
- ✅ All environment variables in Config class are documented
- ✅ Docker configuration matches Dockerfile
- ✅ Package dependencies match functionality described
### Example Verification
- ✅ Distance tracker example aligns with sample files
- ✅ Import/export operations match schema definitions
- ✅ Permission queries match schema definitions
## Recommendations for Improvement
1. Add missing environment variables and their purposes
2. Clarify the subscription functionality status
3. Expand on the relationship between Zabbix entities and GraphQL types
4. Include more information about the code generation process
5. Add troubleshooting section with common issues
6. Include performance considerations and scaling information
7. Add security best practices section
8. Include backup and recovery procedures

View file

@ -0,0 +1,57 @@
### 3.1 Code Generation Section
- Explain the GraphQL Codegen setup and how to regenerate types
- Document the `codegen.ts` configuration
- Add instructions for updating generated types after schema changes
## Priority 4: Improve Examples
### 4.1 Complete Examples
- Add more complete examples for each major operation
- Include error handling examples
- Add examples for common use cases beyond the distance tracker
### 4.2 Testing Examples
- Add information about how to run tests
- Include examples of unit and integration tests
- Explain the test structure and how to add new tests
## Priority 5: Documentation Links
### 5.1 Cross-Reference Improvements
- Add links to relevant sections in schema files
- Include references to specific resolver implementations
- Link to related documentation files in the docs directory
### 5.2 External Resources
- Link to official Zabbix API documentation
- Include references to Apollo Server documentation
- Add links to GraphQL best practices
## Priority 6: Maintenance Items
### 6.1 Update Placeholder Values
- Replace all "your-" placeholder values with more descriptive examples
- Add realistic example values for configuration parameters
- Include sample output where appropriate
### 6.2 Version Compatibility Matrix
- Create a matrix showing compatibility between API versions and Zabbix versions
- Include Node.js version compatibility information
- Add information about breaking changes between versions
## Implementation Order
1. Address Priority 1 items first (critical missing information)
2. Update existing sections to be more accurate
3. Add new sections incrementally
4. Enhance examples with more practical use cases
5. Add documentation links and cross-references
6. Perform final review and testing of all examples
## Success Metrics
- All environment variables documented
- Accurate representation of features
- Complete working examples
- Clear architecture and configuration guidance
- Comprehensive troubleshooting information
- Proper cross-references to codebase