vultr-dns-manager/lib/vultr-api.ts
2025-03-16 07:38:30 -06:00

232 lines
5.9 KiB
TypeScript

'use client';
// Types for Vultr API responses
export interface VultrDomain {
domain: string;
date_created: string;
}
export interface VultrDNSRecord {
id: string;
type: string;
name: string;
data: string;
priority?: number;
ttl: number;
}
// Class to interact with Vultr API through our server-side proxy
export class VultrAPI {
private apiKey: string | null = null;
constructor() {
// Check if we're in a browser environment
if (typeof window !== 'undefined') {
// Try to get API key from cookie
this.apiKey = this.getCookie('vultr_api_key');
}
}
// Helper to get cookie value
private getCookie(name: string): string | null {
if (typeof document === 'undefined') return null;
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
return null;
}
// Set API key and store in cookie
async setApiKey(apiKey: string): Promise<void> {
try {
// Validate API key by making a test request to our server proxy
const response = await fetch('/api/vultr', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ apiKey }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Invalid API key');
}
this.apiKey = apiKey;
return;
} catch (error) {
console.error('Error setting API key:', error);
throw error;
}
}
// Clear API key and cookie
async logout(): Promise<void> {
try {
await fetch('/api/vultr', {
method: 'DELETE',
});
this.apiKey = null;
return;
} catch (error) {
console.error('Error logging out:', error);
throw error;
}
}
// Check if API key is set
isAuthenticated(): boolean {
return !!this.apiKey;
}
// Get all domains
async getDomains(): Promise<VultrDomain[]> {
try {
const response = await fetch('/api/vultr/domains');
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to fetch domains');
}
const data = await response.json();
return data.domains;
} catch (error) {
console.error('Error fetching domains:', error);
throw error;
}
}
// Create a new domain
async createDomain(domain: string, serverIp: string): Promise<VultrDomain> {
try {
const response = await fetch('/api/vultr/domains', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
domain,
serverip: serverIp,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to create domain');
}
const data = await response.json();
return data.domain;
} catch (error) {
console.error('Error creating domain:', error);
throw error;
}
}
// Get DNS records for a domain
async getDNSRecords(domain: string): Promise<VultrDNSRecord[]> {
try {
const response = await fetch(`/api/vultr/domains/${domain}/records`);
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || `Failed to fetch DNS records for ${domain}`);
}
const data = await response.json();
return data.records;
} catch (error) {
console.error(`Error fetching DNS records for ${domain}:`, error);
throw error;
}
}
// Create a new DNS record
async createDNSRecord(
domain: string,
record: Omit<VultrDNSRecord, 'id'>
): Promise<VultrDNSRecord> {
try {
const response = await fetch(`/api/vultr/domains/${domain}/records`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(record),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || `Failed to create DNS record for ${domain}`);
}
const data = await response.json();
return data.record;
} catch (error) {
console.error(`Error creating DNS record for ${domain}:`, error);
throw error;
}
}
// Update an existing DNS record
async updateDNSRecord(
domain: string,
recordId: string,
record: Omit<VultrDNSRecord, 'id'>
): Promise<VultrDNSRecord> {
try {
const response = await fetch(`/api/vultr/domains/${domain}/records/${recordId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(record),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || `Failed to update DNS record ${recordId}`);
}
const data = await response.json();
return data.record;
} catch (error) {
console.error(`Error updating DNS record ${recordId}:`, error);
throw error;
}
}
// Delete a DNS record
async deleteDNSRecord(domain: string, recordId: string): Promise<void> {
try {
const response = await fetch(`/api/vultr/domains/${domain}/records/${recordId}`, {
method: 'DELETE',
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || `Failed to delete DNS record ${recordId}`);
}
return;
} catch (error) {
console.error(`Error deleting DNS record ${recordId}:`, error);
throw error;
}
}
}
// Singleton instance
let vultrApiInstance: VultrAPI | null = null;
export function getVultrApi(): VultrAPI {
if (!vultrApiInstance) {
vultrApiInstance = new VultrAPI();
}
return vultrApiInstance;
}