Overview

Globals & Advanced API Patterns

System-wide configuration and advanced usage patterns for the Picos Health API.

Globals Overview

Globals are singleton documents storing site-wide configuration.

SiteSettings

Endpoint: GET/POST /globals/site-settings

curl https://api.picoshealth.com/v1/globals/site-settings

Response:

{
  "id": "site-settings-global",
  "siteName": "Picos Health",
  "siteDescription": "Healthcare delivered with care",
  "supportEmail": "support@picoshealth.com",
  "contactPhone": "1-800-PICOS-01"
}

OrganizationSettings

Endpoint: GET/POST /globals/organization-settings

Organization tier, user limits, feature flags, and network summary.

MessageSettings

Endpoint: GET/POST /globals/message-settings

Configuration for email, SMS, and push notifications.

Wallet

Endpoint: GET/POST /globals/wallet

Payment system configuration including auto-charge settings and fees.


Caching Requests

In-Memory Cache with TTL

class CachedAPI {
  constructor(ttl = 60000) {
    this.cache = new Map();
    this.ttl = ttl;
  }
  
  async fetch(url, options) {
    const cacheKey = `${options?.method || 'GET'}:${url}`;
    
    if (!options?.method || options.method === 'GET') {
      if (this.cache.has(cacheKey)) {
        const { data, timestamp } = this.cache.get(cacheKey);
        if (Date.now() - timestamp < this.ttl) {
          return data;
        }
      }
    }
    
    const response = await fetch(url, options);
    const data = await response.json();
    
    if (!options?.method || options.method === 'GET') {
      this.cache.set(cacheKey, { data, timestamp: Date.now() });
    }
    
    return data;
  }
  
  invalidate(pattern) {
    for (const key of this.cache.keys()) {
      if (key.includes(pattern)) {
        this.cache.delete(key);
      }
    }
  }
}

Rate Limiting & Queuing

Rate Limited Queue

class RateLimitedQueue {
  constructor(maxRequests = 100, windowMs = 60000) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
    this.requests = [];
    this.queue = [];
  }
  
  async add(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn, resolve, reject });
      this.process();
    });
  }
  
  async process() {
    if (this.queue.length === 0) return;
    
    const now = Date.now();
    this.requests = this.requests.filter(time => now - time < this.windowMs);
    
    if (this.requests.length >= this.maxRequests) {
      setTimeout(() => this.process(), 100);
      return;
    }
    
    const { fn, resolve, reject } = this.queue.shift();
    this.requests.push(now);
    
    try {
      const result = await fn();
      resolve(result);
    } catch (error) {
      reject(error);
    }
    
    if (this.queue.length > 0) {
      setTimeout(() => this.process(), 0);
    }
  }
}

Batch Operations

// Batch create multiple users
const batchCreateUsers = async (token, users) => {
  const promises = users.map(user =>
    fetch('https://api.picoshealth.com/v1/users', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(user),
    }).then(r => r.json())
  );
  
  return Promise.all(promises);
};

Pagination Helper

// Fetch all results with automatic pagination
const fetchAll = async (url, headers, limit = 100) => {
  let allDocs = [];
  let page = 1;
  let hasMore = true;
  
  while (hasMore) {
    const response = await fetch(`${url}?limit=${limit}&page=${page}`, { headers });
    const data = await response.json();
    
    allDocs = allDocs.concat(data.docs);
    hasMore = page < data.totalPages;
    page++;
  }
  
  return allDocs;
};

Webhook Processing

const handleWebhook = (event) => {
  const { collection, operation, doc } = event;
  
  switch (`${collection}:${operation}`) {
    case 'orders:create':
      console.log('New order created:', doc.id);
      break;
    case 'orders:update':
      if (doc.status === 'shipped') {
        console.log('Order shipped:', doc.id);
      }
      break;
    default:
      console.log('Unhandled webhook:', event);
  }
};

Best Practices

Performance

  1. Use depth parameter wisely - Only expand relationships when needed
  2. Filter server-side - Use where clauses for filtering
  3. Paginate large datasets - Never fetch all at once
  4. Cache aggressively - Global data changes infrequently
  5. Batch operations - Group requests when possible

Security

  1. Never commit tokens - Use environment variables
  2. Always use HTTPS - In production
  3. Rotate tokens regularly - Refresh every hour
  4. Validate inputs - Client-side validation too
  5. Audit access - Log all requests

Last Updated: June 22, 2026

Previous
API Overview