TypeScript SDK
The official TypeScript/JavaScript SDK for Sparbz Cloud.
Installation
npm install @sparbzcloud/sdk
# or
bun add @sparbzcloud/sdk
# or
yarn add @sparbzcloud/sdk
Works with Node.js 18+, Bun, and modern browsers.
Quick Start
import { SparbzCloud } from '@sparbzcloud/sdk';
const client = new SparbzCloud({
apiKey: 'szc_prod_...'
});
// List all databases
const databases = await client.databases.list();
for (const db of databases) {
console.log(`Database: ${db.name} (${db.status})`);
}
Configuration
API Key Authentication
const client = new SparbzCloud({
apiKey: 'szc_prod_...'
});
JWT Token Authentication
const client = new SparbzCloud({
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
});
All Options
const client = new SparbzCloud({
apiKey: 'szc_prod_...',
baseUrl: 'https://api.sparbz.cloud',
timeout: 30000,
retries: 3,
logger: console,
});
Environment Variables
export SPARBZ_API_KEY="szc_prod_..."
export SPARBZ_API_URL="https://api.sparbz.cloud"
// Uses environment variables automatically
const client = new SparbzCloud();
Databases
List Databases
const databases = await client.databases.list();
// With filters
const databases = await client.databases.list({
engine: 'postgres',
status: 'active'
});
Create Database
const db = await client.databases.create({
name: 'my-database',
engine: 'postgres',
tier: 'pro'
});
console.log(`Created database: ${db.id}`);
Get Database
const db = await client.databases.get('db_abc123');
Delete Database
await client.databases.delete('db_abc123', {
skipFinalBackup: false
});
Get Credentials
const creds = await client.databases.getCredentials('db_abc123');
console.log(`Connection string: ${creds.connectionString}`);
Wait for Ready State
const db = await client.databases.create({
name: 'my-database',
engine: 'postgres'
});
// Wait up to 10 minutes for database to be ready
const readyDb = await client.databases.waitReady(db.id, {
timeout: 600000,
pollInterval: 5000
});
Namespaces
List Namespaces
const namespaces = await client.namespaces.list();
Create Namespace
const ns = await client.namespaces.create({
name: 'my-app',
tier: 'starter'
});
Get Kubeconfig
const kubeconfig = await client.namespaces.getKubeconfig('ns_abc123');
await fs.writeFile('kubeconfig.yaml', kubeconfig);
Apply Manifest
const manifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
`;
const result = await client.namespaces.apply('ns_abc123', manifest);
for (const resource of result.applied) {
console.log(`Applied: ${resource.kind}/${resource.name}`);
}
List Resources
// List deployments
const deployments = await client.namespaces.listDeployments('ns_abc123');
// List pods
const pods = await client.namespaces.listPods('ns_abc123');
// List services
const services = await client.namespaces.listServices('ns_abc123');
Storage
List Buckets
const buckets = await client.storage.list();
Create Bucket
const bucket = await client.storage.create({
name: 'my-bucket',
region: 'us-east'
});
Get Credentials
const creds = await client.storage.getCredentials('bucket_abc123');
console.log(`Access Key: ${creds.accessKeyId}`);
console.log(`Secret Key: ${creds.secretAccessKey}`);
console.log(`Endpoint: ${creds.endpoint}`);
Generate Presigned URL
const url = await client.storage.presignedUrl('bucket_abc123', {
key: 'uploads/file.pdf',
method: 'PUT',
expiresIn: 3600
});
Using with AWS SDK
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const creds = await client.storage.getCredentials('bucket_abc123');
const s3 = new S3Client({
endpoint: creds.endpoint,
region: 'us-east-1',
credentials: {
accessKeyId: creds.accessKeyId,
secretAccessKey: creds.secretAccessKey
},
forcePathStyle: true
});
await s3.send(new PutObjectCommand({
Bucket: 'my-bucket',
Key: 'file.txt',
Body: 'Hello, World!'
}));
Kafka
List Clusters
const clusters = await client.kafka.list();
Create Cluster
const cluster = await client.kafka.create({
name: 'my-kafka',
tier: 'pro'
});
// Wait for cluster to be ready
const readyCluster = await client.kafka.waitReady(cluster.id);
Manage Topics
// Create topic
const topic = await client.kafka.createTopic('cluster_id', {
name: 'orders',
partitions: 6,
replicas: 3
});
// List topics
const topics = await client.kafka.listTopics('cluster_id');
// Delete topic
await client.kafka.deleteTopic('cluster_id', 'orders');
Manage Users
// Create user
const user = await client.kafka.createUser('cluster_id', {
name: 'my-app'
});
// Get credentials
const creds = await client.kafka.getUserCredentials('cluster_id', user.id);
console.log(`Username: ${creds.username}`);
console.log(`Password: ${creds.password}`);
Using with KafkaJS
import { Kafka } from 'kafkajs';
const creds = await client.kafka.getCredentials('cluster_id');
const kafka = new Kafka({
clientId: 'my-app',
brokers: creds.bootstrapServers.split(','),
ssl: true,
sasl: {
mechanism: 'scram-sha-512',
username: creds.username,
password: creds.password
}
});
const producer = kafka.producer();
await producer.connect();
await producer.send({
topic: 'orders',
messages: [{ value: JSON.stringify({ orderId: '123' }) }]
});
Vault
List Secrets
const secrets = await client.vault.list('secret/data/my-app');
Write Secret
await client.vault.write('secret/data/my-app/config', {
api_key: 'sk_live_...',
database_url: 'postgres://...'
});
Read Secret
const secret = await client.vault.read('secret/data/my-app/config');
const apiKey = secret.data.api_key;
Delete Secret
await client.vault.delete('secret/data/my-app/config');
Stacks
Create Stack
const stack = await client.stacks.create({
name: 'my-app',
tenant: 'acme-corp',
template: {
version: '1',
name: 'my-app',
resources: {
database: {
type: 'database',
properties: {
engine: 'postgres',
version: '15'
}
}
}
}
});
Apply Stack
const execution = await client.stacks.apply(stack.id, {
dryRun: false
});
// Wait for completion
const result = await client.stacks.waitExecution(stack.id, execution.id);
if (result.status === 'completed') {
console.log('Stack deployed successfully!');
}
Get Outputs
const outputs = await client.stacks.getOutputs(stack.id);
for (const [name, output] of Object.entries(outputs)) {
if (!output.sensitive) {
console.log(`${name} = ${output.value}`);
}
}
Error Handling
import { SparbzCloud, APIError, NotFoundError, RateLimitError } from '@sparbzcloud/sdk';
try {
const db = await client.databases.get('db_abc123');
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Database not found');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited, retry after ${error.retryAfter} seconds`);
} else if (error instanceof APIError) {
console.log(`API error: ${error.message} (${error.code})`);
} else {
throw error;
}
}
Error Types
| Error | Description |
|---|---|
APIError | Base error for all API errors |
NotFoundError | Resource not found (404) |
UnauthorizedError | Invalid credentials (401) |
ForbiddenError | Insufficient permissions (403) |
ValidationError | Invalid request data (400) |
RateLimitError | Rate limit exceeded (429) |
ServerError | Server error (5xx) |
Pagination
Automatic Iteration
// Iterate over all databases
for await (const db of client.databases.listAll()) {
console.log(`Database: ${db.name}`);
}
Manual Pagination
let page = 1;
while (true) {
const result = await client.databases.list({ page, perPage: 20 });
for (const db of result.data) {
console.log(`Database: ${db.name}`);
}
if (page >= result.meta.totalPages) break;
page++;
}
Request Cancellation
const controller = new AbortController();
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
const db = await client.databases.create(
{ name: 'my-db', engine: 'postgres' },
{ signal: controller.signal }
);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request cancelled');
}
}
TypeScript Types
import type {
Database,
DatabaseCreateRequest,
Namespace,
KafkaCluster,
KafkaTopic,
StorageBucket,
Stack,
StackTemplate
} from '@sparbzcloud/sdk';
const createDatabase = async (options: DatabaseCreateRequest): Promise<Database> => {
return client.databases.create(options);
};
Logging
const client = new SparbzCloud({
apiKey: 'szc_prod_...',
logger: {
debug: (msg, data) => console.debug(msg, data),
info: (msg, data) => console.info(msg, data),
warn: (msg, data) => console.warn(msg, data),
error: (msg, data) => console.error(msg, data)
}
});
Testing
Use the mock client for testing:
import { createMockClient } from '@sparbzcloud/sdk/testing';
const mockClient = createMockClient();
mockClient.databases.list.mockResolvedValue([
{ id: 'db_test123', name: 'test-db', status: 'active' }
]);
// Use mockClient in your tests
const databases = await mockClient.databases.list();
expect(databases).toHaveLength(1);
expect(databases[0].name).toBe('test-db');
Complete Example
import { SparbzCloud } from '@sparbzcloud/sdk';
async function main() {
const client = new SparbzCloud();
// Create a database
const db = await client.databases.create({
name: 'my-app-db',
engine: 'postgres',
tier: 'starter'
});
console.log(`Created database: ${db.id}`);
// Wait for it to be ready
const readyDb = await client.databases.waitReady(db.id);
// Get connection credentials
const creds = await client.databases.getCredentials(db.id);
console.log(`Connection string: ${creds.connectionString}`);
// Store credentials in Vault
await client.vault.write('secret/data/my-app/database', {
connection_string: creds.connectionString
});
console.log('Credentials stored in Vault');
// Create a namespace for the app
const ns = await client.namespaces.create({
name: 'my-app',
tier: 'starter'
});
// Apply Kubernetes manifest
await client.namespaces.apply(ns.id, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 2
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-app:latest
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: my-app-secrets
key: database_url
`);
console.log('Application deployed!');
}
main().catch(console.error);
Browser Usage
The SDK works in browsers with some limitations:
import { SparbzCloud } from '@sparbzcloud/sdk';
// In browser, use token auth (not API keys for security)
const client = new SparbzCloud({
token: userToken
});
const databases = await client.databases.list();
Note: API keys should never be used in browser code. Use JWT tokens obtained through user authentication.