Skip to main content

JavaScript Examples

JavaScript/Node.js integration examples for the CuliUptime API using session-based authentication.

📦 Installation

npm install axios
# Note: Official CuliUptime JavaScript SDK is planned for future release

🔐 Authentication Approach

CuliUptime uses OAuth2 social login. For JavaScript integrations, you can:

  1. Web Dashboard Integration: Use embedded web views for OAuth2 flow
  2. Session-based API: Extract session cookies from authenticated browser sessions
  3. Future SDK: Wait for official JavaScript SDK with OAuth2 support

🟨 Session-Based JavaScript Client

Basic Client Class (Node.js)

const axios = require('axios');

class CuliUptimeAPI {
constructor(sessionCookie, baseURL = 'https://uptime.culiops.net/api/v1') {
this.baseURL = baseURL;
this.client = axios.create({
baseURL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': `session_cookie=${sessionCookie}`
},
withCredentials: true
});
}

async request(method, endpoint, data = null) {
try {
const response = await this.client.request({
method,
url: endpoint,
data
});
return response.data;
} catch (error) {
if (error.response) {
throw new Error(`API Error: ${error.response.status} - ${error.response.statusText}`);
}
throw error;
}
}

// Monitor Management
async getMonitors(params = {}) {
const response = await this.request('GET', '/monitors', null);
return response.data || [];
}

async getMonitor(monitorId) {
const response = await this.request('GET', `/monitors/${monitorId}`);
return response.data || {};
}

async createMonitor(monitorData) {
const response = await this.request('POST', '/monitors', monitorData);
return response.data || {};
}

async updateMonitor(monitorId, updates) {
const response = await this.request('PUT', `/monitors/${monitorId}`, updates);
return response.data || {};
}

async deleteMonitor(monitorId) {
await this.request('DELETE', `/monitors/${monitorId}`);
return true;
}

async enableMonitor(monitorId) {
const response = await this.request('POST', `/monitors/${monitorId}/enable`);
return response;
}

async disableMonitor(monitorId) {
const response = await this.request('POST', `/monitors/${monitorId}/disable`);
return response;
}

async testMonitor(monitorId) {
const response = await this.request('POST', `/monitors/${monitorId}/test`);
return response.data || {};
}

async getMonitorResults(monitorId, params = {}) {
const queryParams = new URLSearchParams(params).toString();
const endpoint = `/monitors/${monitorId}/results${queryParams ? `?${queryParams}` : ''}`;
const response = await this.request('GET', endpoint);
return response.data || [];
}

async getMonitorStats(monitorId) {
const response = await this.request('GET', `/monitors/${monitorId}/stats`);
return response.data || {};
}

// Agent Management
async getAgents() {
const response = await this.request('GET', '/agents');
return response.data || [];
}

async getAccessibleAgents() {
const response = await this.request('GET', '/agents/accessible');
return response.data || [];
}

async getAgent(agentId) {
const response = await this.request('GET', `/agents/${agentId}`);
return response.data || {};
}

async assignAgentsToMonitor(monitorId, agentIds) {
const response = await this.request('POST', `/monitors/${monitorId}/agents`, { agent_ids: agentIds });
return response;
}

// Notifications
async getActiveNotifications() {
const response = await this.request('GET', '/notifications/active');
return response.data || [];
}

async getRecentNotifications() {
const response = await this.request('GET', '/notifications/recent');
return response.data || [];
}

async getNotifications(params = {}) {
const queryParams = new URLSearchParams(params).toString();
const endpoint = `/notifications${queryParams ? `?${queryParams}` : ''}`;
const response = await this.request('GET', endpoint);
return response.data || [];
}

async acknowledgeNotification(notificationId) {
const response = await this.request('POST', `/notifications/${notificationId}/acknowledge`);
return response;
}

// User & Dashboard
async getCurrentUser() {
const response = await this.request('GET', '/auth/user');
return response.data || {};
}

async getDashboardData() {
const response = await this.request('GET', '/dashboard');
return response.data || {};
}

async getUserPreferences() {
const response = await this.request('GET', '/preferences');
return response.data || {};
}

async updateUserPreferences(preferences) {
const response = await this.request('PUT', '/preferences', preferences);
return response.data || {};
}
}

module.exports = CuliUptimeAPI;

Browser Client (Vanilla JavaScript)

class CuliUptimeAPI {
constructor(baseURL = 'https://uptime.culiops.net/api/v1') {
this.baseURL = baseURL;
}

async request(method, endpoint, data = null) {
const options = {
method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'include' // Include cookies automatically
};

if (data) {
options.body = JSON.stringify(data);
}

const response = await fetch(`${this.baseURL}${endpoint}`, options);

if (!response.ok) {
throw new Error(`API Error: ${response.status} - ${response.statusText}`);
}

return response.json();
}

// Monitor operations
async getMonitors(params = {}) {
const queryParams = new URLSearchParams(params).toString();
const endpoint = `/monitors${queryParams ? `?${queryParams}` : ''}`;
const response = await this.request('GET', endpoint);
return response.data || [];
}

async createMonitor(monitorData) {
const response = await this.request('POST', '/monitors', monitorData);
return response.data || {};
}

async updateMonitor(monitorId, updates) {
const response = await this.request('PUT', `/monitors/${monitorId}`, updates);
return response.data || {};
}

async deleteMonitor(monitorId) {
await this.request('DELETE', `/monitors/${monitorId}`);
return true;
}

async testMonitor(monitorId) {
const response = await this.request('POST', `/monitors/${monitorId}/test`);
return response.data || {};
}

// Dashboard operations
async getDashboardData() {
const response = await this.request('GET', '/dashboard');
return response.data || {};
}

async getActiveNotifications() {
const response = await this.request('GET', '/notifications/active');
return response.data || [];
}
}

🚀 Usage Examples

Initialize Client

// Node.js - Initialize with session cookie from browser
const CuliUptimeAPI = require('./culiuptime-client');
const api = new CuliUptimeAPI('your_session_cookie_value');

// Browser - Automatically uses cookies
const api = new CuliUptimeAPI();

Monitor Management

async function manageMonitors() {
try {
// Get all monitors
const monitors = await api.getMonitors();
console.log(`Found ${monitors.length} monitors`);

// Get online monitors only
const onlineMonitors = await api.getMonitors({ status: 'online' });

// Search monitors
const apiMonitors = await api.getMonitors({ search: 'api' });

// Create new HTTP monitor
const newMonitor = await api.createMonitor({
name: 'My API Endpoint',
url: 'https://api.example.com/health',
method: 'GET',
expected_status: [200, 201],
timeout: 30,
check_interval: 300
});

console.log(`Created monitor with ID: ${newMonitor.id}`);

// Update monitor
const updatedMonitor = await api.updateMonitor(newMonitor.id, {
check_interval: 600,
timeout: 45
});

// Test monitor immediately
const testResult = await api.testMonitor(newMonitor.id);
console.log(`Monitor status: ${testResult.status}`);

// Get monitor statistics
const stats = await api.getMonitorStats(newMonitor.id);
console.log(`Uptime: ${stats.uptime_24h || 0}%`);

} catch (error) {
console.error('Monitor management error:', error.message);
}
}

Notification Handling

async function handleNotifications() {
try {
// Check for active alerts
const activeNotifications = await api.getActiveNotifications();

if (activeNotifications.length > 0) {
console.log(`⚠️ ${activeNotifications.length} active notifications:`);

for (const notification of activeNotifications) {
console.log(` - ${notification.message}`);

// Acknowledge notification
await api.acknowledgeNotification(notification.id);
console.log(` ✅ Acknowledged notification ${notification.id}`);
}
}

// Get notification history
const recentNotifications = await api.getRecentNotifications();
console.log(`Recent notifications: ${recentNotifications.length}`);

} catch (error) {
console.error('Notification handling error:', error.message);
}
}

Agent Management

async function manageAgents() {
try {
// Get available agents
const agents = await api.getAccessibleAgents();
console.log(`Available agents: ${agents.length}`);

agents.forEach(agent => {
console.log(` - ${agent.name} (${agent.location}) - Status: ${agent.status}`);
});

// Assign agents to monitor
const monitors = await api.getMonitors();
if (agents.length >= 2 && monitors.length > 0) {
const agentIds = agents.slice(0, 2).map(agent => agent.id); // Use first 2 agents
const monitorId = monitors[0].id; // Use first monitor

await api.assignAgentsToMonitor(monitorId, agentIds);
console.log(`Assigned ${agentIds.length} agents to monitor ${monitorId}`);
}

} catch (error) {
console.error('Agent management error:', error.message);
}
}

Dashboard Integration

async function displayDashboard() {
try {
// Get dashboard overview
const dashboard = await api.getDashboardData();

console.log('📊 Dashboard Overview:');
console.log(` - Total Monitors: ${dashboard.total_monitors || 0}`);
console.log(` - Online: ${dashboard.online_monitors || 0}`);
console.log(` - Offline: ${dashboard.offline_monitors || 0}`);
console.log(` - Average Uptime: ${(dashboard.average_uptime || 0).toFixed(2)}%`);

} catch (error) {
console.error('Dashboard error:', error.message);
}
}

🔄 Advanced Usage

Error Handling

class CuliUptimeError extends Error {
constructor(message, statusCode = null) {
super(message);
this.name = 'CuliUptimeError';
this.statusCode = statusCode;
}
}

// Enhanced client with error handling
class EnhancedCuliUptimeAPI extends CuliUptimeAPI {
async request(method, endpoint, data = null) {
try {
return await super.request(method, endpoint, data);
} catch (error) {
if (error.response) {
const status = error.response.status;
if (status === 401) {
throw new CuliUptimeError('Authentication failed - session expired', 401);
} else if (status === 429) {
throw new CuliUptimeError('Rate limit exceeded', 429);
} else if (status >= 500) {
throw new CuliUptimeError('Server error occurred', status);
}
}
throw new CuliUptimeError(`API error: ${error.message}`);
}
}
}

// Usage with error handling
async function safeApiCall() {
const api = new EnhancedCuliUptimeAPI('your_session_cookie');

try {
const monitors = await api.getMonitors();
console.log(`Successfully retrieved ${monitors.length} monitors`);
} catch (error) {
if (error instanceof CuliUptimeError) {
console.error(`API Error (${error.statusCode}): ${error.message}`);
} else {
console.error(`Unexpected error: ${error.message}`);
}
}
}

Batch Operations

async function batchUpdateMonitors(api, updates) {
const results = [];

for (const update of updates) {
const { id, ...data } = update;
try {
const result = await api.updateMonitor(id, data);
results.push({ status: 'success', id, result });
} catch (error) {
results.push({ status: 'error', id, error: error.message });
}
}

return results;
}

// Example batch update
const updates = [
{ id: 123, check_interval: 300 },
{ id: 124, timeout: 45 },
{ id: 125, check_interval: 600 }
];

const results = await batchUpdateMonitors(api, updates);
results.forEach(result => {
console.log(`Monitor ${result.id}: ${result.status}`);
});

Monitor Health Checker

async function checkMonitorHealth(api, monitorId) {
try {
const monitor = await api.getMonitor(monitorId);
const stats = await api.getMonitorStats(monitorId);
const recentResults = await api.getMonitorResults(monitorId);

const healthReport = {
monitor_id: monitorId,
name: monitor.name,
url: monitor.url,
status: monitor.status,
uptime_24h: stats.uptime_24h || 0,
avg_response_time: stats.avg_response_time || 0,
recent_failures: recentResults.slice(0, 10).filter(r => r.status !== 'online').length,
health_score: stats.uptime_24h > 99 ? 'excellent' : stats.uptime_24h > 95 ? 'good' : 'poor'
};

return healthReport;
} catch (error) {
throw new Error(`Health check failed: ${error.message}`);
}
}

// Generate health report
const health = await checkMonitorHealth(api, 123);
console.log(`
🏥 Health Report for ${health.name}:
Status: ${health.status}
24h Uptime: ${health.uptime_24h.toFixed(2)}%
Avg Response Time: ${health.avg_response_time}ms
Recent Failures: ${health.recent_failures}/10
Health Score: ${health.health_score}
`);

// Manual cookie extraction (for development)
function getSessionCookieFromBrowser() {
/*
Instructions for extracting session cookie:

1. Open browser and login to CuliUptime dashboard
2. Open Developer Tools (F12)
3. Go to Application/Storage tab
4. Click on Cookies
5. Find 'session_cookie' and copy its value
6. Use the value to initialize the API client
*/
const sessionCookie = prompt("Enter session cookie from browser:");
return sessionCookie;
}

// For automated browser workflows (requires Puppeteer)
async function automatedLogin(email, password) {
// Note: This would require implementing OAuth2 flow
// which is complex and not recommended for production
throw new Error("Automated OAuth2 login not implemented");
}

Session Validation

async function validateSession(api) {
try {
const user = await api.getCurrentUser();
return !!user.id;
} catch (error) {
return false;
}
}

// Check session validity
if (await validateSession(api)) {
console.log('✅ Session is valid');
} else {
console.log('❌ Session expired or invalid');
}

Note: For production applications, consider implementing a proper OAuth2 flow or wait for the official CuliUptime JavaScript SDK which will handle authentication securely.