feat(apiclient): add typed, object-oriented API client documentation and interfaces; document builders, resource managers, and new programmatic endpoints

This commit is contained in:
2026-03-06 08:01:05 +00:00
parent aaf3c9cb1c
commit d5dfe439c7
8 changed files with 436 additions and 15 deletions

110
readme.md
View File

@@ -26,6 +26,7 @@ For reporting bugs, issues, or security vulnerabilities, please visit [community
- [Storage & Caching](#storage--caching)
- [Security Features](#security-features)
- [OpsServer Dashboard](#opsserver-dashboard)
- [API Client](#api-client)
- [API Reference](#api-reference)
- [Sub-Modules](#sub-modules)
- [Testing](#testing)
@@ -90,6 +91,13 @@ For reporting bugs, issues, or security vulnerabilities, please visit [community
- **Remote ingress management** with connection token generation and one-click copy
- **Read-only configuration display** — DcRouter is configured through code
### 🔧 Programmatic API Client
- **Object-oriented API** — resource classes (`Route`, `Certificate`, `ApiToken`, `RemoteIngress`, `Email`) with instance methods
- **Builder pattern** — fluent `.setName().setMatch().save()` chains for creating routes, tokens, and edges
- **Auto-injected auth** — JWT identity and API tokens included automatically in every request
- **Dual auth modes** — login with credentials (JWT) or pass an API token for programmatic access
- **Full coverage** — wraps every OpsServer endpoint with typed request/response pairs
## Installation
```bash
@@ -1038,12 +1046,9 @@ All management is done via TypedRequest over HTTP POST to `/typedrequest`:
'getCombinedMetrics' // All metrics in one call
// Email Operations
'getQueuedEmails' // Emails pending delivery
'getSentEmails' // Successfully delivered emails
'getFailedEmails' // Failed emails
'getAllEmails' // List all emails (queued/sent/failed)
'getEmailDetail' // Full detail for a specific email
'resendEmail' // Re-queue a failed email
'getBounceRecords' // Bounce records
'removeFromSuppressionList' // Unsuppress an address
// Certificates
'getCertificateOverview' // Domain-centric certificate status
@@ -1062,11 +1067,28 @@ All management is done via TypedRequest over HTTP POST to `/typedrequest`:
'getRemoteIngressStatus' // Runtime status of all edges
'getRemoteIngressConnectionToken' // Generate a connection token for an edge
// Route Management (JWT or API token auth)
'getMergedRoutes' // List all routes (hardcoded + programmatic)
'createRoute' // Create a new programmatic route
'updateRoute' // Update a programmatic route
'deleteRoute' // Delete a programmatic route
'toggleRoute' // Enable/disable a programmatic route
'setRouteOverride' // Override a hardcoded route
'removeRouteOverride' // Remove a hardcoded route override
// API Token Management (admin JWT only)
'createApiToken' // Create API token → returns raw value once
'listApiTokens' // List all tokens (without secrets)
'revokeApiToken' // Delete an API token
'rollApiToken' // Regenerate token secret
'toggleApiToken' // Enable/disable a token
// Configuration (read-only)
'getConfiguration' // Current system config
// Logs
'getLogs' // Retrieve system logs
'getRecentLogs' // Retrieve system logs with filtering
'getLogStream' // Stream live logs
// RADIUS
'getRadiusSessions' // Active RADIUS sessions
@@ -1080,6 +1102,77 @@ All management is done via TypedRequest over HTTP POST to `/typedrequest`:
'testVlanAssignment' // Test what VLAN a MAC gets
```
## API Client
DcRouter ships with a typed, object-oriented API client for programmatic management of a running instance. Install it separately or import from the main package:
```bash
pnpm add @serve.zone/dcrouter-apiclient
# or import from the main package:
# import { DcRouterApiClient } from '@serve.zone/dcrouter/apiclient';
```
### Quick Example
```typescript
import { DcRouterApiClient } from '@serve.zone/dcrouter/apiclient';
const client = new DcRouterApiClient({ baseUrl: 'https://dcrouter.example.com' });
await client.login('admin', 'password');
// OO resource instances with methods
const { routes } = await client.routes.list();
await routes[0].toggle(false);
// Builder pattern for creation
const newRoute = await client.routes.build()
.setName('api-gateway')
.setMatch({ ports: 443, domains: ['api.example.com'] })
.setAction({ type: 'forward', targets: [{ host: 'backend', port: 8080 }] })
.setTls({ mode: 'terminate', certificate: 'auto' })
.save();
// Manage certificates
const { certificates, summary } = await client.certificates.list();
await certificates[0].reprovision();
// Create API tokens with builder
const token = await client.apiTokens.build()
.setName('ci-token')
.setScopes(['routes:read', 'routes:write'])
.setExpiresInDays(90)
.save();
console.log(token.tokenValue); // only available at creation
// Remote ingress edges
const edge = await client.remoteIngress.build()
.setName('edge-nyc-01')
.setListenPorts([80, 443])
.save();
const connToken = await edge.getConnectionToken();
// Read-only managers
const health = await client.stats.getHealth();
const config = await client.config.get();
const { logs } = await client.logs.getRecent({ level: 'error', limit: 50 });
```
### Resource Managers
| Manager | Operations |
|---------|-----------|
| `client.routes` | `list()`, `create()`, `build()` → Route: `update()`, `delete()`, `toggle()`, `setOverride()`, `removeOverride()` |
| `client.certificates` | `list()`, `import()` → Certificate: `reprovision()`, `delete()`, `export()` |
| `client.apiTokens` | `list()`, `create()`, `build()` → ApiToken: `revoke()`, `roll()`, `toggle()` |
| `client.remoteIngress` | `list()`, `getStatuses()`, `create()`, `build()` → RemoteIngress: `update()`, `delete()`, `regenerateSecret()`, `getConnectionToken()` |
| `client.stats` | `getServer()`, `getEmail()`, `getDns()`, `getSecurity()`, `getConnections()`, `getQueues()`, `getHealth()`, `getNetwork()`, `getCombined()` |
| `client.config` | `get(section?)` |
| `client.logs` | `getRecent()`, `getStream()` |
| `client.emails` | `list()` → Email: `getDetail()`, `resend()` |
| `client.radius` | `.clients`, `.vlans`, `.sessions` sub-managers + `getStatistics()`, `getAccountingSummary()` |
See the [full API client documentation](./ts_apiclient/readme.md) for detailed usage of every manager, builder, and resource class.
## API Reference
### DcRouter Class
@@ -1144,12 +1237,14 @@ DcRouter is published as a monorepo with separately-installable interface and we
|---------|-------------|---------|
| [`@serve.zone/dcrouter`](https://www.npmjs.com/package/@serve.zone/dcrouter) | Main package — the full router | `pnpm add @serve.zone/dcrouter` |
| [`@serve.zone/dcrouter-interfaces`](https://www.npmjs.com/package/@serve.zone/dcrouter-interfaces) | TypedRequest interfaces for the OpsServer API | `pnpm add @serve.zone/dcrouter-interfaces` |
| [`@serve.zone/dcrouter-apiclient`](https://www.npmjs.com/package/@serve.zone/dcrouter-apiclient) | OO API client with builder pattern | `pnpm add @serve.zone/dcrouter-apiclient` |
| [`@serve.zone/dcrouter-web`](https://www.npmjs.com/package/@serve.zone/dcrouter-web) | Web dashboard components | `pnpm add @serve.zone/dcrouter-web` |
You can also import interfaces directly from the main package:
You can also import directly from the main package:
```typescript
import { data, requests } from '@serve.zone/dcrouter/interfaces';
import { DcRouterApiClient } from '@serve.zone/dcrouter/apiclient';
```
## Testing
@@ -1171,6 +1266,7 @@ tstest test/test.opsserver-api.ts --verbose --timeout 60
| Test File | Area | Tests |
|-----------|------|-------|
| `test.apiclient.ts` | API client instantiation, builders, resource hydration, exports | 18 |
| `test.contentscanner.ts` | Content scanning (spam, phishing, malware, attachments) | 13 |
| `test.dcrouter.email.ts` | Email config, domain and route setup | 4 |
| `test.dns-server-config.ts` | DNS record parsing, grouping, extraction | 5 |