Skip to content

Latest commit

 

History

History
502 lines (394 loc) · 16.5 KB

File metadata and controls

502 lines (394 loc) · 16.5 KB

DataCoreX Integration Guide

Your Organization Profile

Authentication Methods

1. Organization-Level Authentication

Use for administrative operations:

curl -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     http://localhost:8081/api/endpoint

2. User-Level Authentication (JWT)

For user-specific operations:

# Login to get token
curl -X POST http://localhost:8081/api/auth/login \
     -H "Content-Type: application/json" \
     -d '{"username":"your_username","password":"your_password"}'

# Use token in requests
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     http://localhost:8081/api/endpoint

3. Organization Login

For organization dashboard access:

curl -X POST http://localhost:8081/api/organization/login \
     -H "Content-Type: application/json" \
     -d '{"email":"admin@test.com","password":"password123"}'

Available Services

🔹 User Management

  • Register User: POST /api/auth/register
  • Login User: POST /api/auth/login
  • Get User Info: GET /api/auth/me
  • User Operations: GET /api/users

🔹 Storage Management

  • Upload Files: POST /api/storage/upload
  • List Files: GET /api/storage/files
  • Download Files: GET /api/storage/files/{id}/download
  • File Search: GET /api/storage/search?query=filename

🔹 Real-time Database

  • Create Document: POST /api/realtime-db/organizations/{orgId}/collections/{collection}/documents
  • Get Document: GET /api/realtime-db/organizations/{orgId}/collections/{collection}/documents/{docId}
  • Query Collection: POST /api/realtime-db/organizations/{orgId}/collections/{collection}/query

🔹 Real-time Communication

  • WebSocket Connection: ws://localhost:8081/ws
  • Send to User: POST /api/realtime/send-to-user
  • Broadcast Message: POST /api/realtime/broadcast
  • Live Data Updates: POST /api/realtime/live-data

🔹 Cloud Functions

  • Deploy Function: POST /api/functions/deploy
  • Execute Function: POST /api/functions/execute/{functionId}
  • List Functions: GET /api/functions/list/{organizationId}

🔹 Firebase Integration

  • Push Notifications: POST /api/firebase/send-notification
  • Topic Notifications: POST /api/firebase/send-to-topic
  • Multicast: POST /api/firebase/send-multicast

🔹 Monitoring & Analytics

  • Activity Logs: GET /api/activity-logs
  • System Health: GET /api/health
  • System Info: GET /api/system/info
  • System Metrics: GET /api/system/metrics
  • Current Metrics: GET /api/realtime-data/metrics/current
  • Metric History: GET /api/realtime-data/metrics/{metricName}/history
  • Usage Stats: GET /api/billing/organizations/{orgId}/stats
  • Usage Limits: GET /api/billing/organizations/{orgId}/limits/check

🔹 Node Management

  • List Nodes: GET /api/nodes
  • Add Node: POST /api/nodes
  • Get Node: GET /api/nodes/{id}
  • Update Node: PUT /api/nodes/{id}
  • Delete Node: DELETE /api/nodes/{id}
  • Update Health: POST /api/nodes/{id}/health

🔹 API Key Management

  • Create API Key: POST /api/keys
  • Validate API Key: POST /api/keys/validate
  • Get Organization Keys: GET /api/keys/organization/{organizationId}
  • Deactivate Key: DELETE /api/keys/{id}

🔹 System Management

  • Execute Script: POST /api/system/scripts/execute
  • Available Scripts: GET /api/system/scripts
  • Start Maintenance: POST /api/system/maintenance/start
  • Stop Maintenance: POST /api/system/maintenance/stop

🔹 Debug & Development

  • System Information: GET /api/debug/system-info
  • Environment Variables: GET /api/debug/environment
  • Recent Errors: GET /api/debug/errors
  • Test Logging: POST /api/debug/test-log
  • Garbage Collection: POST /api/debug/gc

Example Website Integration

Frontend JavaScript Example

class DataCoreXClient {
  constructor() {
    this.baseUrl = 'http://localhost:8081'
    this.apiKey = 'dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q'
    this.organizationId = 1
  }

  async authenticateUser(username, password) {
    const response = await fetch(`${this.baseUrl}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password }),
    })
    const data = await response.json()
    if (data.success) {
      localStorage.setItem('dcx_token', data.token)
      return data.user
    }
    throw new Error(data.message)
  }

  async uploadFile(file) {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch(`${this.baseUrl}/api/storage/upload`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('dcx_token')}`,
      },
      body: formData,
    })
    return response.json()
  }

  async createDocument(collection, data) {
    const response = await fetch(
      `${this.baseUrl}/api/realtime-db/organizations/${this.organizationId}/collections/${collection}/documents`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${localStorage.getItem('dcx_token')}`,
        },
        body: JSON.stringify(data),
      }
    )
    return response.json()
  }

  connectWebSocket() {
    const ws = new WebSocket(`ws://localhost:8081/ws`)
    ws.onopen = () => console.log('Connected to DataCoreX real-time')
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data)
      this.handleRealtimeUpdate(data)
    }
    return ws
  }

  handleRealtimeUpdate(data) {
    // Handle real-time updates in your website
    console.log('Real-time update:', data)
  }
}

// Usage
const dcx = new DataCoreXClient()

Backend Integration (Node.js Example)

const axios = require('axios')

class DataCoreXServer {
  constructor() {
    this.baseUrl = 'http://localhost:8081'
    this.apiKey = 'dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q'
    this.organizationId = 1
  }

  async deployFunction(name, code, runtime = 'javascript') {
    try {
      const response = await axios.post(
        `${this.baseUrl}/api/functions/deploy?name=${name}&runtime=${runtime}&organizationId=${this.organizationId}`,
        { code },
        {
          headers: {
            'X-API-Key': this.apiKey,
            'Content-Type': 'application/json',
          },
        }
      )
      return response.data
    } catch (error) {
      console.error('Function deployment failed:', error.response?.data)
      throw error
    }
  }

  async trackUsage(eventType, metadata = {}) {
    try {
      const response = await axios.post(
        `${this.baseUrl}/api/realtime-data/publish`,
        {
          dataType: 'usage_tracking',
          data: {
            organizationId: this.organizationId,
            eventType,
            timestamp: new Date().toISOString(),
            metadata,
          },
        },
        {
          headers: {
            'X-API-Key': this.apiKey,
            'Content-Type': 'application/json',
          },
        }
      )
      return response.data
    } catch (error) {
      console.error('Usage tracking failed:', error.response?.data)
    }
  }
}

Testing Your Integration

1. Test Organization Login

curl -X POST http://localhost:8081/api/organization/login \
     -H "Content-Type: application/json" \
     -d '{"email":"admin@test.com","password":"password123"}'

2. Test User Registration

curl -X POST http://localhost:8081/api/auth/register \
     -H "Content-Type: application/json" \
     -d '{"username":"websiteuser","email":"user@yourwebsite.com","password":"password123","role":"USER"}'

3. Test Health Check

curl http://localhost:8081/api/health

4. Test API Documentation

Open in browser: http://localhost:8081/api-docs

5. Test Real-time Database

# Create a document in a collection
curl -X POST "http://localhost:8081/api/realtime-db/organizations/1/collections/users/documents" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     -d '{"name":"John Doe","email":"john@example.com","created":"2025-01-01"}'

# Query documents
curl -X POST "http://localhost:8081/api/realtime-db/organizations/1/collections/users/query" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     -d '{"where":{"name":"John Doe"}}'

6. Test System Monitoring

# Get system metrics
curl -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     http://localhost:8081/api/system/metrics

# Get real-time data statistics
curl http://localhost:8081/api/realtime-data/statistics

7. Test Cloud Functions

# Deploy a simple function
curl -X POST "http://localhost:8081/api/functions/deploy?name=hello&runtime=javascript&organizationId=1" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     -d '{"code":"function main(input) { return {message: \"Hello \" + (input.name || \"World\")}; }"}'

# List functions for your organization
curl -H "X-API-Key: dcx_UvYRRWRpRhpDSH6PMXAyVkrCiFYxGa7Q" \
     http://localhost:8081/api/functions/list/1

Production Deployment

When moving to production:

  1. Update baseUrl to your production DataCoreX server
  2. Use HTTPS endpoints
  3. Store API keys securely (environment variables)
  4. Implement proper error handling
  5. Set up monitoring and logging

Need Help?

Complete API Endpoint Reference

Organization Management

  • POST /api/organization/register - Register new organization
  • POST /api/organization/login - Organization authentication
  • GET /api/organization/profile/{organizationId} - Get organization profile
  • POST /api/organization/regenerate-api-key/{organizationId} - Regenerate API key

User Authentication & Management

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User authentication
  • POST /api/auth/logout - User logout
  • POST /api/auth/verify-token - Verify JWT token
  • GET /api/auth/me - Get current user info
  • GET /api/users - List all users
  • PATCH /api/users/{id} - Update user
  • DELETE /api/users/{id} - Delete user

Storage Management

  • POST /api/storage/upload - Upload file
  • POST /api/storage/upload-url - Generate pre-signed upload URL
  • GET /api/storage/files - List all files
  • GET /api/storage/files/my - Get current user's files
  • GET /api/storage/files/{id} - Get file details
  • GET /api/storage/files/{id}/download - Download file
  • DELETE /api/storage/files/{id} - Delete file
  • GET /api/storage/search - Search files by filename
  • GET /api/storage/stats - Get storage statistics

Real-time Database

  • POST /api/realtime-db/organizations/{orgId}/collections/{collection}/documents - Create document
  • GET /api/realtime-db/organizations/{orgId}/collections/{collection}/documents/{docId} - Get document
  • PUT /api/realtime-db/organizations/{orgId}/collections/{collection}/documents/{docId} - Update document
  • DELETE /api/realtime-db/organizations/{orgId}/collections/{collection}/documents/{docId} - Delete document
  • POST /api/realtime-db/organizations/{orgId}/collections/{collection}/query - Query collection
  • GET /api/realtime-db/organizations/{orgId}/stats - Get real-time stats

Real-time Communication

  • GET /api/realtime/status - Get real-time service status
  • GET /api/realtime/connections - Get active WebSocket connections
  • POST /api/realtime/system-notification - Send system notification
  • POST /api/realtime/send-to-user - Send message to specific user
  • POST /api/realtime/send-to-channel - Send message to channel
  • POST /api/realtime/broadcast - Broadcast to all connected clients
  • POST /api/realtime/live-data - Send live data updates

Real-time Data & Analytics

  • POST /api/realtime-data/publish - Publish data to streams
  • POST /api/realtime-data/metrics - Record custom metric
  • POST /api/realtime-data/metrics/node-performance - Record node performance
  • GET /api/realtime-data/statistics - Get service statistics
  • GET /api/realtime-data/metrics/current - Get current metrics
  • GET /api/realtime-data/metrics/{metricName}/history - Get metric history
  • GET /api/realtime-data/metrics/{metricName}/summary - Get metric summary
  • GET /api/realtime-data/cached-data - Get all cached data
  • GET /api/realtime-data/cached-data/{dataType} - Get cached data by type

Cloud Functions

  • POST /api/functions/deploy - Deploy serverless function
  • POST /api/functions/execute/{functionId} - Execute function
  • GET /api/functions/{functionId} - Get function details
  • GET /api/functions/{functionId}/logs - Get function execution logs
  • DELETE /api/functions/{functionId} - Delete function
  • GET /api/functions/list/{organizationId} - List organization functions
  • GET /api/functions/health - Check functions service health

Firebase Integration

  • POST /api/firebase/send-notification - Send push notification
  • POST /api/firebase/send-multicast - Send to multiple devices
  • POST /api/firebase/send-to-topic - Send to topic subscribers
  • POST /api/firebase/subscribe-to-topic - Subscribe device to topic
  • POST /api/firebase/unsubscribe-from-topic - Unsubscribe from topic
  • POST /api/firebase/validate-token - Validate device token
  • GET /api/firebase/status - Get Firebase service status

Node Management

  • GET /api/nodes - List all nodes
  • POST /api/nodes - Add new node
  • GET /api/nodes/{id} - Get node details
  • PUT /api/nodes/{id} - Update node
  • DELETE /api/nodes/{id} - Delete node
  • POST /api/nodes/{id}/health - Update node health

System Management

  • GET /api/system/health - System health check
  • GET /api/system/info - System information
  • GET /api/system/metrics - System metrics
  • GET /api/system/scripts - Available scripts
  • POST /api/system/scripts/execute - Execute system script
  • POST /api/system/maintenance/start - Start maintenance mode
  • POST /api/system/maintenance/stop - Stop maintenance mode

Activity Logs

  • GET /api/activity-logs - Get all activity logs (paginated)
  • GET /api/activity-logs/{id} - Get specific log entry
  • GET /api/activity-logs/user/{userId} - Get logs by user
  • GET /api/activity-logs/level/{level} - Get logs by level
  • GET /api/activity-logs/category/{category} - Get logs by category
  • GET /api/activity-logs/action/{action} - Get logs by action
  • GET /api/activity-logs/search - Search logs by description
  • GET /api/activity-logs/date-range - Get logs within date range
  • GET /api/activity-logs/statistics - Get log statistics
  • DELETE /api/activity-logs/cleanup - Cleanup old logs

Billing & Usage

  • GET /api/billing/organizations/{orgId}/usage/current - Current month usage
  • GET /api/billing/organizations/{orgId}/usage - Usage for date range
  • GET /api/billing/organizations/{orgId}/stats - Usage statistics
  • GET /api/billing/organizations/{orgId}/limits/check - Check usage limits

API Key Management

  • POST /api/keys - Create new API key
  • POST /api/keys/validate - Validate API key
  • GET /api/keys/organization/{organizationId} - Get organization keys
  • DELETE /api/keys/{id} - Deactivate API key

Debug & Development

  • GET /api/debug/health - Application health check
  • GET /api/debug/system-info - System and JVM information
  • GET /api/debug/environment - Environment variables
  • GET /api/debug/errors - Recent error logs
  • POST /api/debug/test-log - Create test log entry
  • POST /api/debug/gc - Trigger garbage collection

Script Execution

  • POST /api/scripts/run - Run custom script

Monitoring & Health

  • POST /api/monitoring/health - Get health score
  • GET /api/info - API information
  • GET /api/health - Health check endpoint
  • GET /api/audit - Audit logs

Your DataCoreX BaaS platform is ready for integration! 🚀