← back to Omega Watches 2

src/app/api/william/route.ts

64 lines

import { NextRequest, NextResponse } from 'next/server';

const WILLIAM_URL = 'http://127.0.0.1:9601';
const AUTH = 'Basic ' + Buffer.from('admin:DWSecure2024!').toString('base64');

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const action = searchParams.get('action');

  try {
    let endpoint = '/api/observations';
    if (action === 'status') endpoint = '/health';
    else if (action === 'market') endpoint = '/api/market-summary';

    const res = await fetch(`${WILLIAM_URL}${endpoint}`, {
      headers: { Authorization: AUTH },
      cache: 'no-store',
    });

    if (!res.ok) {
      return NextResponse.json(
        { error: 'William is not responding', observations: [] },
        { status: 502 }
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch {
    return NextResponse.json(
      { error: 'Cannot reach William', observations: [], status: 'offline' },
      { status: 502 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const action = body.action || 'trigger';

    let endpoint = '/api/trigger';
    if (action === 'pause') endpoint = '/api/pause';
    else if (action === 'resume') endpoint = '/api/resume';

    const res = await fetch(`${WILLIAM_URL}${endpoint}`, {
      method: 'POST',
      headers: {
        Authorization: AUTH,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    const data = await res.json();
    return NextResponse.json(data);
  } catch {
    return NextResponse.json(
      { error: 'Cannot reach William' },
      { status: 502 }
    );
  }
}