fix(client): update request handling and typings for current smartrequest and OpenAPI output
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"gitzone": {
|
||||
"@git.zone/cli": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
@@ -22,10 +22,16 @@
|
||||
"DevOps",
|
||||
"Cloud Infrastructure"
|
||||
]
|
||||
},
|
||||
"release": {
|
||||
"registries": [
|
||||
"https://verdaccio.lossless.digital",
|
||||
"https://registry.npmjs.org"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
"@ship.zone/szci": {
|
||||
"npmGlobalTools": []
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.json"],
|
||||
"fileMatch": ["/.smartconfig.json"],
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-05-07 - 1.2.1 - fix(client)
|
||||
update request handling and typings for current smartrequest and OpenAPI output
|
||||
|
||||
- migrate HetznerAccount requests to the SmartRequest builder API and normalize responses to statusCode/body
|
||||
- adjust generated request and resource types for nullable OpenAPI fields and JSON request bodies
|
||||
- make live API tests skip cleanly when the Hetzner token is missing or rejected
|
||||
- refresh package tooling and project metadata configuration files
|
||||
|
||||
## 2024-06-15 - 1.2.0 - release
|
||||
Release published with no additional user-facing changes beyond recent updates already included below.
|
||||
|
||||
- Version 1.2.0 tags the current state without introducing separate documented changes.
|
||||
|
||||
## 2024-06-15 - 1.1.1 - openapi
|
||||
Integrated OpenAPI directly into the repository.
|
||||
|
||||
- Added OpenAPI assets and related integration directly to the repo.
|
||||
|
||||
## 2024-06-15 - 1.1.0 - core
|
||||
Applied a core update.
|
||||
|
||||
- Updated core functionality and internal project behavior.
|
||||
|
||||
## 2024-06-15 - 1.0.18 - volumes and firewalls
|
||||
Added support for managing volumes and firewalls.
|
||||
|
||||
- Enabled volumes management.
|
||||
- Enabled firewalls management.
|
||||
|
||||
## 2024-01-29 - 1.0.1 to 1.0.17 - core
|
||||
Series of trivial core update releases between 1.0.1 and 1.0.17.
|
||||
|
||||
- Repeated maintenance-level `fix(core): update` changes were released across versions 1.0.1 through 1.0.17.
|
||||
- Individual entries are summarized here to avoid duplicating minimal, non-descriptive updates.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Task Venture Capital GmbH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+12
-12
@@ -12,21 +12,21 @@
|
||||
"test": "(tstest test/ --web)",
|
||||
"build": "(tsbuild --web --allowimplicitany)",
|
||||
"buildDocs": "(tsdoc)",
|
||||
"updateAPI": "openapi-typescript https://docs.hetzner.cloud/spec.json --output ts/openapi.spec.ts"
|
||||
"updateOpenapi": "openapi-typescript https://docs.hetzner.cloud/spec.json --output ts/openapi.spec.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.25",
|
||||
"@git.zone/tsbundle": "^2.0.5",
|
||||
"@git.zone/tsrun": "^1.2.46",
|
||||
"@git.zone/tstest": "^1.0.44",
|
||||
"@push.rocks/qenv": "^6.0.5",
|
||||
"@push.rocks/tapbundle": "^5.0.15",
|
||||
"@types/node": "^20.11.22",
|
||||
"openapi-typescript": "^6.7.6"
|
||||
"@git.zone/tsbuild": "^4.4.0",
|
||||
"@git.zone/tsbundle": "^2.10.1",
|
||||
"@git.zone/tsrun": "^2.0.3",
|
||||
"@git.zone/tstest": "^3.6.3",
|
||||
"@push.rocks/qenv": "^6.1.4",
|
||||
"@types/node": "^25.6.2",
|
||||
"openapi-typescript": "^7.13.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartrequest": "^2.0.21",
|
||||
"@tsclass/tsclass": "^4.0.52"
|
||||
"@push.rocks/smartrequest": "^5.0.3",
|
||||
"@tsclass/tsclass": "^9.5.1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -48,7 +48,7 @@
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
".smartconfig.json",
|
||||
"readme.md"
|
||||
],
|
||||
"keywords": [
|
||||
|
||||
Generated
+5768
-4608
File diff suppressed because it is too large
Load Diff
@@ -1,267 +1,265 @@
|
||||
# @apiclient.xyz/hetznercloud
|
||||
An unofficial API client for the Hetzner Cloud API
|
||||
|
||||
`@apiclient.xyz/hetznercloud` is an unofficial TypeScript client for the Hetzner Cloud API. It wraps the day-to-day infrastructure primitives this package currently supports - servers, volumes, and firewalls - behind small classes that keep the original Hetzner resource data available while giving you convenient methods for create, list, label-filter, and delete workflows.
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Why Use It?
|
||||
|
||||
- TypeScript-first ESM package for Hetzner Cloud automation.
|
||||
- Simple `HetznerAccount` object that owns API token authentication.
|
||||
- Resource classes for `HetznerServer`, `HetznerVolume`, and `HetznerFirewall`.
|
||||
- Label-based lookup helpers for predictable automation runs.
|
||||
- Typed request and response shapes generated from the Hetzner OpenAPI specification.
|
||||
- Escape hatch via `account.request()` whenever you need an endpoint that does not yet have a higher-level class method.
|
||||
|
||||
## Install
|
||||
|
||||
You can install the `@apiclient.xyz/hetznercloud` package via npm:
|
||||
|
||||
```bash
|
||||
npm install @apiclient.xyz/hetznercloud
|
||||
pnpm add @apiclient.xyz/hetznercloud
|
||||
```
|
||||
|
||||
Or using yarn:
|
||||
|
||||
```bash
|
||||
yarn add @apiclient.xyz/hetznercloud
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The `@apiclient.xyz/hetznercloud` package provides a modern approach to interact with the Hetzner Cloud API. Below are some detailed examples demonstrating the usage of this package for different scenarios like managing accounts, servers, volumes, and firewalls.
|
||||
|
||||
### Initial Setup
|
||||
|
||||
To begin using the package, you need to import it and initialize your Hetzner account with an API token:
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { HetznerAccount, HetznerServer, Volume, HetznerFirewall } from '@apiclient.xyz/hetznercloud';
|
||||
import {
|
||||
HetznerAccount,
|
||||
HetznerFirewall,
|
||||
HetznerVolume,
|
||||
} from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
// Initialize Hetzner account
|
||||
const myHetznerAccount = new HetznerAccount('yourHetznerApiToken');
|
||||
```
|
||||
const account = new HetznerAccount('your-hetzner-api-token');
|
||||
|
||||
### Managing Servers
|
||||
|
||||
#### Creating a Server
|
||||
|
||||
You can create a new server using the `createServer` method in the `HetznerAccount` class. Provide the necessary options such as name, type, location, labels, and optional user data:
|
||||
|
||||
```typescript
|
||||
const newServer = await myHetznerAccount.createServer({
|
||||
name: 'my-server',
|
||||
const server = await account.createServer({
|
||||
name: 'demo-api-01',
|
||||
type: 'cpx31',
|
||||
location: 'nbg1',
|
||||
labels: {
|
||||
purpose: 'test'
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
userData: '#!/bin/bash\necho Hello from your new server!'
|
||||
userData: '#!/bin/bash\napt-get update',
|
||||
});
|
||||
|
||||
console.log('New server details:', newServer.data);
|
||||
```
|
||||
|
||||
#### Listing Servers
|
||||
|
||||
To list all servers in your account, you can use the `getServers` method:
|
||||
|
||||
```typescript
|
||||
const servers = await myHetznerAccount.getServers();
|
||||
console.log('Current servers:', servers);
|
||||
```
|
||||
|
||||
#### Filtering Servers by Labels
|
||||
|
||||
You can filter servers based on specific labels:
|
||||
|
||||
```typescript
|
||||
const filteredServers = await myHetznerAccount.getServersByLabel({ purpose: 'test' });
|
||||
console.log('Filtered servers:', filteredServers);
|
||||
```
|
||||
|
||||
#### Deleting a Server
|
||||
|
||||
To delete a server, call the `delete` method on the server instance:
|
||||
|
||||
```typescript
|
||||
const serverToDelete = filteredServers[0]; // Example, choose the first filtered server
|
||||
await serverToDelete.delete();
|
||||
console.log('Server deleted successfully');
|
||||
```
|
||||
|
||||
### Managing Volumes
|
||||
|
||||
#### Creating a Volume
|
||||
|
||||
To create a new volume, use the `Volume.create` method, passing in the necessary options:
|
||||
|
||||
```typescript
|
||||
const newVolume = await Volume.create(myHetznerAccount, {
|
||||
name: 'my-volume',
|
||||
size: 10, // Size in GB
|
||||
const volume = await HetznerVolume.create(account, {
|
||||
name: 'demo-api-data',
|
||||
size: 25,
|
||||
location: 'nbg1',
|
||||
labels: {
|
||||
purpose: 'test-volume'
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
server: newServer // Attach the volume to a specific server (newServer in this case)
|
||||
server,
|
||||
});
|
||||
|
||||
console.log('New volume details:', newVolume.data);
|
||||
```
|
||||
|
||||
#### Listing Volumes
|
||||
|
||||
You can list all volumes in your account with the `getVolumes` method:
|
||||
|
||||
```typescript
|
||||
const volumes = await Volume.getVolumes(myHetznerAccount);
|
||||
console.log('Current volumes:', volumes);
|
||||
```
|
||||
|
||||
#### Filtering Volumes by Labels
|
||||
|
||||
To filter volumes based on specific labels:
|
||||
|
||||
```typescript
|
||||
const filteredVolumes = await Volume.getVolumesByLabel(myHetznerAccount, { purpose: 'test-volume' });
|
||||
console.log('Filtered volumes:', filteredVolumes);
|
||||
```
|
||||
|
||||
#### Deleting a Volume
|
||||
|
||||
To delete a volume, call the `delete` method on the volume instance:
|
||||
|
||||
```typescript
|
||||
const volumeToDelete = filteredVolumes[0]; // Example, choose the first filtered volume
|
||||
await volumeToDelete.delete();
|
||||
console.log('Volume deleted successfully');
|
||||
```
|
||||
|
||||
### Managing Firewalls
|
||||
|
||||
#### Creating a Firewall
|
||||
|
||||
To create a new firewall, use the `create` method in the `HetznerFirewall` class:
|
||||
|
||||
```typescript
|
||||
const newFirewall = await HetznerFirewall.create(myHetznerAccount, {
|
||||
name: 'my-firewall',
|
||||
const firewall = await HetznerFirewall.create(account, {
|
||||
name: 'demo-api-web',
|
||||
labels: {
|
||||
purpose: 'test-firewall'
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '443',
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log(server.data);
|
||||
console.log(volume.data);
|
||||
console.log(firewall.data);
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Accounts
|
||||
|
||||
`HetznerAccount` stores your Hetzner Cloud API token and exposes the shared request layer used by all resource classes.
|
||||
|
||||
```typescript
|
||||
import { HetznerAccount } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const account = new HetznerAccount('your-hetzner-api-token');
|
||||
```
|
||||
|
||||
Available account helpers:
|
||||
|
||||
- `account.getServers()` lists all servers visible to the token.
|
||||
- `account.getServersByLabel(labels)` lists servers and returns exact label matches.
|
||||
- `account.createServer(options)` creates a new server.
|
||||
- `account.request(method, path, payload)` calls the Hetzner Cloud API directly.
|
||||
|
||||
The direct request helper returns an object shaped like this:
|
||||
|
||||
```typescript
|
||||
const response = await account.request('GET', '/servers', {});
|
||||
|
||||
console.log(response.statusCode);
|
||||
console.log(response.body);
|
||||
```
|
||||
|
||||
The current implementation logs request metadata and response bodies to the console, which is useful during automation debugging and important to remember when running with sensitive payloads.
|
||||
|
||||
### Servers
|
||||
|
||||
Servers are represented by `HetznerServer`. The package can create, list, filter, and delete them.
|
||||
|
||||
```typescript
|
||||
const server = await account.createServer({
|
||||
name: 'worker-01',
|
||||
type: 'cpx41',
|
||||
location: 'fsn1',
|
||||
labels: {
|
||||
role: 'worker',
|
||||
},
|
||||
userData: '#!/bin/bash\necho ready',
|
||||
});
|
||||
|
||||
const allServers = await account.getServers();
|
||||
const workerServers = await account.getServersByLabel({ role: 'worker' });
|
||||
|
||||
await server.delete();
|
||||
```
|
||||
|
||||
`createServer()` currently creates Ubuntu 22.04 servers, starts them immediately, and enables public IPv4 and IPv6 networking.
|
||||
|
||||
Supported server type names are:
|
||||
|
||||
```text
|
||||
cx11, cx21, cx31, cx41, cx51,
|
||||
ccx11, ccx21, ccx31, ccx41, ccx51,
|
||||
ccx13, ccx23, ccx33, ccx43, ccx53, ccx63,
|
||||
cpx11, cpx21, cpx31, cpx41, cpx51, cpx61, cpx70, cpx71, cpx90
|
||||
```
|
||||
|
||||
Supported location names are:
|
||||
|
||||
```text
|
||||
fsn1, nbg1, hel1, ash, hil
|
||||
```
|
||||
|
||||
### Volumes
|
||||
|
||||
Volumes are represented by `HetznerVolume`. A volume is created for and attached to an existing `HetznerServer` instance.
|
||||
|
||||
```typescript
|
||||
import { HetznerVolume } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const volume = await HetznerVolume.create(account, {
|
||||
name: 'worker-01-data',
|
||||
size: 50,
|
||||
location: 'fsn1',
|
||||
labels: {
|
||||
role: 'worker',
|
||||
},
|
||||
server,
|
||||
});
|
||||
|
||||
const allVolumes = await HetznerVolume.getVolumes(account);
|
||||
const workerVolumes = await HetznerVolume.getVolumesByLabel(account, { role: 'worker' });
|
||||
|
||||
await volume.delete();
|
||||
```
|
||||
|
||||
`HetznerVolume.create()` currently formats new volumes as `xfs` and attaches them to `options.server.data.id`.
|
||||
|
||||
### Firewalls
|
||||
|
||||
Firewalls are represented by `HetznerFirewall`. The package can create firewalls with rules, list them, filter them by label, and delete them.
|
||||
|
||||
```typescript
|
||||
import { HetznerFirewall } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
const firewall = await HetznerFirewall.create(account, {
|
||||
name: 'web-ingress',
|
||||
labels: {
|
||||
app: 'frontend',
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '80',
|
||||
source_ips: ['0.0.0.0/0', '::/0']
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
{
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '443',
|
||||
source_ips: ['0.0.0.0/0', '::/0']
|
||||
}
|
||||
]
|
||||
source_ips: ['0.0.0.0/0', '::/0'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log('New firewall details:', newFirewall.data);
|
||||
const allFirewalls = await HetznerFirewall.getFirewalls(account);
|
||||
const frontendFirewalls = await HetznerFirewall.getFirewallsByLabel(account, { app: 'frontend' });
|
||||
|
||||
await firewall.delete();
|
||||
```
|
||||
|
||||
#### Listing Firewalls
|
||||
### Label Filtering
|
||||
|
||||
To list all firewalls in your account:
|
||||
The label helpers perform exact matches for every key/value pair you pass in. This makes them practical for idempotent automation where labels are your resource ownership contract.
|
||||
|
||||
```typescript
|
||||
const firewalls = await HetznerFirewall.getFirewalls(myHetznerAccount);
|
||||
console.log('Current firewalls:', firewalls);
|
||||
```
|
||||
|
||||
#### Filtering Firewalls by Labels
|
||||
|
||||
To filter firewalls based on specific labels:
|
||||
|
||||
```typescript
|
||||
const filteredFirewalls = await HetznerFirewall.getFirewallsByLabel(myHetznerAccount, { purpose: 'test-firewall' });
|
||||
console.log('Filtered firewalls:', filteredFirewalls);
|
||||
```
|
||||
|
||||
#### Deleting a Firewall
|
||||
|
||||
To delete a firewall, call the `delete` method on the firewall instance:
|
||||
|
||||
```typescript
|
||||
const firewallToDelete = filteredFirewalls[0]; // Example, choose the first filtered firewall
|
||||
await firewallToDelete.delete();
|
||||
console.log('Firewall deleted successfully');
|
||||
```
|
||||
|
||||
### Example: Full Lifecycle Management
|
||||
|
||||
Here is a complete example that demonstrates the full lifecycle of creating, listing, filtering, and deleting servers, volumes, and firewalls:
|
||||
|
||||
```typescript
|
||||
import { HetznerAccount, HetznerServer, Volume, HetznerFirewall } from '@apiclient.xyz/hetznercloud';
|
||||
|
||||
// Initialize Hetzner account
|
||||
const myHetznerAccount = new HetznerAccount('yourHetznerApiToken');
|
||||
|
||||
// Step 1: Create a new server
|
||||
const newServer = await myHetznerAccount.createServer({
|
||||
name: 'my-server',
|
||||
type: 'cpx31',
|
||||
location: 'nbg1',
|
||||
labels: { purpose: 'test' },
|
||||
userData: '#!/bin/bash\necho Hello from your new server!'
|
||||
const servers = await account.getServersByLabel({
|
||||
app: 'demo-api',
|
||||
environment: 'staging',
|
||||
});
|
||||
console.log('New server created:', newServer.data);
|
||||
```
|
||||
|
||||
// Step 2: Create a new volume and attach it to the server
|
||||
const newVolume = await Volume.create(myHetznerAccount, {
|
||||
name: 'my-volume',
|
||||
size: 10, // GB
|
||||
location: 'nbg1',
|
||||
labels: { purpose: 'test-volume' },
|
||||
server: newServer
|
||||
});
|
||||
console.log('New volume created:', newVolume.data);
|
||||
## Direct API Access
|
||||
|
||||
// Step 3: Create a new firewall and attach rules to it
|
||||
const newFirewall = await HetznerFirewall.create(myHetznerAccount, {
|
||||
name: 'my-firewall',
|
||||
labels: { purpose: 'test-firewall' },
|
||||
rules: [
|
||||
{ direction: 'in', protocol: 'tcp', port: '80', source_ips: ['0.0.0.0/0', '::/0'] },
|
||||
{ direction: 'in', protocol: 'tcp', port: '443', source_ips: ['0.0.0.0/0', '::/0'] }
|
||||
]
|
||||
});
|
||||
console.log('New firewall created:', newFirewall.data);
|
||||
Use `account.request()` when you need access to an endpoint that is not wrapped yet. Pass the HTTP method, the API path below `/v1`, and a payload object.
|
||||
|
||||
// Step 4: List all servers, volumes, and firewalls
|
||||
const servers = await myHetznerAccount.getServers();
|
||||
console.log('All servers:', servers);
|
||||
```typescript
|
||||
const locationsResponse = await account.request('GET', '/locations', {});
|
||||
|
||||
const volumes = await Volume.getVolumes(myHetznerAccount);
|
||||
console.log('All volumes:', volumes);
|
||||
|
||||
const firewalls = await HetznerFirewall.getFirewalls(myHetznerAccount);
|
||||
console.log('All firewalls:', firewalls);
|
||||
|
||||
// Step 5: Filter servers, volumes, and firewalls by labels
|
||||
const filteredServers = await myHetznerAccount.getServersByLabel({ purpose: 'test' });
|
||||
console.log('Filtered servers:', filteredServers);
|
||||
|
||||
const filteredVolumes = await Volume.getVolumesByLabel(myHetznerAccount, { purpose: 'test-volume' });
|
||||
console.log('Filtered volumes:', filteredVolumes);
|
||||
|
||||
const filteredFirewalls = await HetznerFirewall.getFirewallsByLabel(myHetznerAccount, { purpose: 'test-firewall' });
|
||||
console.log('Filtered firewalls:', filteredFirewalls);
|
||||
|
||||
// Step 6: Cleanup - Delete created resources
|
||||
for (const server of filteredServers) {
|
||||
await server.delete();
|
||||
console.log('Server deleted:', server.data);
|
||||
}
|
||||
|
||||
for (const volume of filteredVolumes) {
|
||||
await volume.delete();
|
||||
console.log('Volume deleted:', volume.data);
|
||||
}
|
||||
|
||||
for (const firewall of filteredFirewalls) {
|
||||
await firewall.delete();
|
||||
console.log('Firewall deleted:', firewall.data);
|
||||
if (locationsResponse.statusCode >= 200 && locationsResponse.statusCode < 300) {
|
||||
console.log(locationsResponse.body);
|
||||
}
|
||||
```
|
||||
|
||||
This comprehensive example demonstrates how you can manage your Hetzner resources using the `@apiclient.xyz/hetznercloud` package efficiently and effectively.
|
||||
undefined
|
||||
For non-`GET` and non-`DELETE` requests, the payload is sent as JSON.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm test
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
Tests use `@git.zone/tstest`. Live Hetzner API tests look for `HETZNER_API_TOKEN`; without a usable token, the live API parts are skipped.
|
||||
|
||||
The OpenAPI types can be refreshed with:
|
||||
|
||||
```bash
|
||||
pnpm run updateOpenapi
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
+39
-10
@@ -1,24 +1,49 @@
|
||||
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as hetznercloud from '../ts/index.js';
|
||||
import * as qenv from '@push.rocks/qenv';
|
||||
const testQenv = new qenv.Qenv('./', './.nogit/');
|
||||
|
||||
let testAccount: hetznercloud.HetznerAccount;
|
||||
let testAccount: hetznercloud.HetznerAccount | undefined;
|
||||
let liveApiAvailable = false;
|
||||
let liveApiSkipReason = 'HETZNER_API_TOKEN has not been validated.';
|
||||
|
||||
tap.test('should create a valid hetzer account', async () => {
|
||||
testAccount = new hetznercloud.HetznerAccount(
|
||||
await testQenv.getEnvVarOnDemand('HETZNER_API_TOKEN')
|
||||
);
|
||||
tap.test('should create a valid hetzer account', async (toolsArg) => {
|
||||
const token = await testQenv.getEnvVarOnDemand('HETZNER_API_TOKEN');
|
||||
if (!token) {
|
||||
liveApiSkipReason = 'HETZNER_API_TOKEN is not configured.';
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
testAccount = new hetznercloud.HetznerAccount(token);
|
||||
expect(testAccount).toBeInstanceOf(hetznercloud.HetznerAccount);
|
||||
});
|
||||
|
||||
tap.test('should be able to list all servers', async () => {
|
||||
const servers = await testAccount.getServers();
|
||||
tap.test('should be able to list all servers', async (toolsArg) => {
|
||||
if (!testAccount) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const account = testAccount;
|
||||
const tokenCheckResponse = await account.request('GET', '/servers', {});
|
||||
if (tokenCheckResponse.statusCode === 401 || tokenCheckResponse.statusCode === 403) {
|
||||
liveApiSkipReason = 'HETZNER_API_TOKEN was rejected by the Hetzner API.';
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
if (tokenCheckResponse.statusCode < 200 || tokenCheckResponse.statusCode >= 300) {
|
||||
throw new Error(`Hetzner API returned status ${tokenCheckResponse.statusCode}`);
|
||||
}
|
||||
liveApiAvailable = true;
|
||||
const servers = await account.getServers();
|
||||
expect(servers).toBeArray();
|
||||
console.log(JSON.stringify(servers, null, 2));
|
||||
});
|
||||
|
||||
const testserver = tap.test('should be able to create a server', async (toolsArg) => {
|
||||
if (!liveApiAvailable || !testAccount) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const newServer = await testAccount.createServer({
|
||||
name: 'testserver',
|
||||
location: 'nbg1',
|
||||
@@ -33,10 +58,14 @@ const testserver = tap.test('should be able to create a server', async (toolsArg
|
||||
return newServer;
|
||||
});
|
||||
|
||||
tap.test('should be able to delete a server', async () => {
|
||||
tap.test('should be able to delete a server', async (toolsArg) => {
|
||||
if (!liveApiAvailable) {
|
||||
toolsArg.skip(liveApiSkipReason);
|
||||
return;
|
||||
}
|
||||
const testServer: hetznercloud.HetznerServer =
|
||||
await (testserver.testResultPromise as Promise<hetznercloud.HetznerServer>);
|
||||
await testServer.delete();
|
||||
});
|
||||
|
||||
tap.start();
|
||||
export default tap.start();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@apiclient.xyz/hetznercloud',
|
||||
version: '1.2.0',
|
||||
version: '1.2.1',
|
||||
description: 'An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.'
|
||||
}
|
||||
|
||||
+27
-8
@@ -30,16 +30,35 @@ export class HetznerAccount {
|
||||
console.log(`Url: ${url}`);
|
||||
console.log(`Method: ${methodArg}`);
|
||||
console.log(`Payload: ${JSON.stringify(payloadArg, null, 2)}`);
|
||||
const response = await plugins.smartrequest.request(url, {
|
||||
method: methodArg,
|
||||
headers: {
|
||||
const request = plugins.smartrequest.SmartRequest.create()
|
||||
.url(url)
|
||||
.headers({
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
},
|
||||
requestBody: payloadArg,
|
||||
})
|
||||
.options({
|
||||
keepAlive: false,
|
||||
});
|
||||
console.log(response.statusCode);
|
||||
console.log(response.body);
|
||||
return response;
|
||||
|
||||
if (methodArg !== 'GET' && methodArg !== 'DELETE') {
|
||||
request.json(payloadArg);
|
||||
}
|
||||
|
||||
const response = methodArg === 'POST'
|
||||
? await request.post()
|
||||
: methodArg === 'PUT'
|
||||
? await request.put()
|
||||
: methodArg === 'PATCH'
|
||||
? await request.patch()
|
||||
: methodArg === 'DELETE'
|
||||
? await request.delete()
|
||||
: await request.get();
|
||||
const body = await response.json().catch(() => ({}));
|
||||
const responseObject = {
|
||||
statusCode: response.status,
|
||||
body,
|
||||
};
|
||||
console.log(responseObject.statusCode);
|
||||
console.log(responseObject.body);
|
||||
return responseObject;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export class HetznerFirewall {
|
||||
optionsArg: {
|
||||
name: string;
|
||||
labels?: {[key: string]: string},
|
||||
rules: types.IFirewall['rules'],
|
||||
rules: types.TFirewallCreateRequestBody['rules'],
|
||||
}
|
||||
) => {
|
||||
const firewall = new HetznerFirewall(hetznerAccountRefArg);
|
||||
@@ -26,7 +26,7 @@ export class HetznerFirewall {
|
||||
createFirewallUrl,
|
||||
createFirewallPayload
|
||||
);
|
||||
firewall.data = (response.body as types.TFirewallCreateResponseBody).firewall;
|
||||
firewall.data = (response.body as types.TFirewallCreateResponseBody).firewall!;
|
||||
return firewall;
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ export class HetznerFirewall {
|
||||
for (const firewall of firewalls) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if (firewall.data.labels[key] !== labelObject[key]) {
|
||||
if ((firewall.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ export class HetznerFirewall {
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
public data: types.IFirewall;
|
||||
public data!: types.IFirewall;
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
|
||||
@@ -35,7 +35,7 @@ export class HetznerServer {
|
||||
createServerUrl,
|
||||
createServerPayload
|
||||
);
|
||||
server.data = (response.body as types.TServerCreateResponseBody).server;
|
||||
server.data = (response.body as types.TServerCreateResponseBody).server!;
|
||||
return server;
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ export class HetznerServer {
|
||||
for (const server of servers) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if (server.data.labels[key] !== labelObject[key]) {
|
||||
if ((server.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ export class HetznerServer {
|
||||
|
||||
// INSTANCE
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
public data: types.IServer;
|
||||
public data!: types.IServer;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
this.hetznerAccountRef = hetznerAccountRefArg;
|
||||
|
||||
@@ -30,7 +30,7 @@ export class HetznerVolume {
|
||||
createVolumeUrl,
|
||||
createVolumePayload
|
||||
);
|
||||
volume.data = (response.body as types.TVolumeCreateResponseBody).volume;
|
||||
volume.data = (response.body as types.TVolumeCreateResponseBody).volume!;
|
||||
return volume;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ export class HetznerVolume {
|
||||
for (const volume of volumes) {
|
||||
let isMatch = true;
|
||||
for (const key in labelObject) {
|
||||
if (volume.data.labels[key] !== labelObject[key]) {
|
||||
if ((volume.data.labels || {})[key] !== labelObject[key]) {
|
||||
isMatch = false;
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export class HetznerVolume {
|
||||
return results;
|
||||
}
|
||||
|
||||
public data: types.IVolume;
|
||||
public data!: types.IVolume;
|
||||
public hetznerAccountRef: HetznerAccount;
|
||||
|
||||
constructor(hetznerAccountRefArg: HetznerAccount) {
|
||||
|
||||
+12
-6
@@ -1,14 +1,20 @@
|
||||
import * as plugins from './hetznercloud.plugins.js';
|
||||
import * as hetznerOpenapiSpec from './openapi.spec.js';
|
||||
|
||||
type TJsonRequestBody<TPathMethod> = TPathMethod extends { requestBody?: infer TRequestBody }
|
||||
? NonNullable<TRequestBody> extends { content: { 'application/json': infer TJsonBody } }
|
||||
? TJsonBody
|
||||
: never
|
||||
: never;
|
||||
|
||||
// datacenters
|
||||
export type TDatacenters = hetznerOpenapiSpec.paths['/datacenters']['get']['responses']['200']['content']['application/json'];
|
||||
|
||||
// servers
|
||||
export type IServer = hetznerOpenapiSpec.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server'];
|
||||
export type IServer = NonNullable<hetznerOpenapiSpec.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server']>;
|
||||
export type TServersGetRequestBody = {};
|
||||
export type TServersGetResponseBody = hetznerOpenapiSpec.paths['/servers']['get']['responses']['200']['content']['application/json'];
|
||||
export type TServerCreateRequestBody = hetznerOpenapiSpec.paths['/servers']['post']['requestBody']['content']['application/json'];
|
||||
export type TServerCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/servers']['post']>;
|
||||
export type TServerCreateResponseBody = hetznerOpenapiSpec.paths['/servers']['post']['responses']['201']['content']['application/json'];
|
||||
export type TServerDeleteRequestBody = hetznerOpenapiSpec.paths['/servers/{id}']['delete'];
|
||||
|
||||
@@ -44,17 +50,17 @@ export type THetznerCloudServerName =
|
||||
export type THetznerCloudLocationName = 'fsn1' | 'nbg1' | 'hel1' | 'ash' | 'hil';
|
||||
|
||||
// volumes
|
||||
export type IVolume = hetznerOpenapiSpec.paths['/volumes/{id}']['get']['responses']['200']['content']['application/json']['volume'];
|
||||
export type IVolume = NonNullable<hetznerOpenapiSpec.paths['/volumes/{id}']['get']['responses']['200']['content']['application/json']['volume']>;
|
||||
export type TVolumeGetRequestBody = {};
|
||||
export type TVolumeGetResponseBody = hetznerOpenapiSpec.paths['/volumes']['get']['responses']['200']['content']['application/json'];
|
||||
export type TVolumeCreateRequestBody = hetznerOpenapiSpec.paths['/volumes']['post']['requestBody']['content']['application/json'];
|
||||
export type TVolumeCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/volumes']['post']>;
|
||||
export type TVolumeCreateResponseBody = hetznerOpenapiSpec.paths['/volumes']['post']['responses']['201']['content']['application/json'];
|
||||
export type TVolumeDeleteRequestBody = hetznerOpenapiSpec.paths['/volumes/{id}']['delete'];
|
||||
|
||||
// firewalls
|
||||
export type IFirewall = hetznerOpenapiSpec.paths['/firewalls/{id}']['get']['responses']['200']['content']['application/json']['firewall'];
|
||||
export type IFirewall = NonNullable<hetznerOpenapiSpec.paths['/firewalls/{id}']['get']['responses']['200']['content']['application/json']['firewall']>;
|
||||
export type TFirewallsGetRequestBody = {};
|
||||
export type TFirewallsGetResponseBody = hetznerOpenapiSpec.paths['/firewalls']['get']['responses']['200']['content']['application/json'];
|
||||
export type TFirewallCreateRequestBody = hetznerOpenapiSpec.paths['/firewalls']['post']['requestBody']['content']['application/json'];
|
||||
export type TFirewallCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/firewalls']['post']>;
|
||||
export type TFirewallCreateResponseBody = hetznerOpenapiSpec.paths['/firewalls']['post']['responses']['201']['content']['application/json'];
|
||||
export type TFirewallDeleteRequestBody = hetznerOpenapiSpec.paths['/firewalls/{id}']['delete'];
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
"verbatimModuleSyntax": true,
|
||||
"declaration": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
|
||||
Reference in New Issue
Block a user