Skip to main content

JavaScript Examples

Node.js

import fs from 'fs';
import path from 'path';

const API_KEY = 'sk_live_xxxxxxxxxxxxx';
const BASE_URL = 'https://stagingspaces-production-6fb7.up.railway.app';

async function stageRoom(imagePath, options = {}) {
  const { style = 'modern', roomType, enhance = false } = options;

  const form = new FormData();
  form.append('image', new Blob([fs.readFileSync(imagePath)]), path.basename(imagePath));
  form.append('style', style);
  if (roomType) form.append('room_type', roomType);
  if (enhance) form.append('enhance_output', 'true');

  const response = await fetch(`${BASE_URL}/api/v1/stage`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${API_KEY}` },
    body: form,
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || `HTTP ${response.status}`);
  }

  return response.json();
}

// Usage
const result = await stageRoom('empty_room.jpg', { style: 'scandinavian' });
console.log(`Staged: ${result.image_url}`);
console.log(`Claim code: ${result.claim_code}`);

Check Credits

async function checkCredits() {
  const response = await fetch(`${BASE_URL}/api/v1/credits`, {
    headers: { 'Authorization': `Bearer ${API_KEY}` },
  });
  return response.json();
}

const { credits } = await checkCredits();
console.log(`Credits remaining: ${credits}`);

Browser (React)

async function stageFromBrowser(file: File, style: string = 'modern') {
  const form = new FormData();
  form.append('image', file);
  form.append('style', style);

  const response = await fetch(
    'https://stagingspaces-production-6fb7.up.railway.app/api/v1/stage',
    {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${API_KEY}` },
      body: form,
    }
  );

  return response.json();
}

// In a React component
function StagingUpload() {
  const [result, setResult] = useState(null);

  const handleUpload = async (e) => {
    const file = e.target.files[0];
    const staged = await stageFromBrowser(file, 'modern');
    setResult(staged);
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleUpload} />
      {result && <img src={result.image_url} alt="Staged" />}
    </div>
  );
}

Batch Staging

async function batchStage(imagePaths, style = 'modern', concurrency = 5) {
  const results = [];
  const chunks = [];

  // Process in chunks to respect rate limits
  for (let i = 0; i < imagePaths.length; i += concurrency) {
    chunks.push(imagePaths.slice(i, i + concurrency));
  }

  for (const chunk of chunks) {
    const batch = await Promise.allSettled(
      chunk.map(img => stageRoom(img, { style }))
    );

    for (const [i, result] of batch.entries()) {
      if (result.status === 'fulfilled') {
        console.log(`✓ ${chunk[i]}${result.value.claim_code}`);
        results.push(result.value);
      } else {
        console.log(`✗ ${chunk[i]}: ${result.reason.message}`);
      }
    }
  }

  return results;
}