top of page

// backend/http-functions.js
import { response } from 'wix-http-functions';
import { fetch } from 'wix-fetch';
import { getSecret } from 'wix-secrets-backend';

// GET  /_functions/atomProxy?path=/api/ping
export async function get_atomProxy(request) {
  return proxy(request, 'GET');
}

// POST /_functions/atomProxy?path=/api/register  (JSON body forwarded)
export async function post_atomProxy(request) {
  return proxy(request, 'POST');
}

async function proxy(request, method) {
  try {
    const { path } = request.query || {};
    if (!path || !String(path).startsWith('/api/')) {
      return bad(400, { error: 'Missing or invalid ?path=/api/...' });
    }

    // IMPORTANT: point this at the host that actually reaches your Atom API
    // e.g. 'https://api.ai1news.com' (recommended) or a direct VPS HTTPS hostname.
    const API_BASE = (await getSecret('ATOM_API_BASE')) || 'https://api.ai1news.com';
    const TOKEN    = await getSecret('ATOM_TOKEN'); // e.g. 'YourTestSuperToken123'

    // Build full target URL, preserve any query already in `path`, then add token
    const target = new URL(path, API_BASE);
    if (TOKEN) target.searchParams.set('token', TOKEN);

    let body;
    const headers = {};
    if (TOKEN) headers['Authorization'] = `Bearer ${TOKEN}`;

    if (method === 'POST') {
      try {
        const text = await request.body.text();
        if (text && text.length) {
          body = text;
          const ctIn = request.headers?.get?.('content-type');
          headers['Content-Type'] = ctIn || 'application/json';
        }
      } catch (e) {
        // no body
      }
    }

    const upstream = await fetch(target.toString(), { method, headers, body });
    const text = await upstream.text();

    return response({
      status: upstream.status,
      headers: {
        'Content-Type': upstream.headers.get('content-type') || 'application/json; charset=utf-8',
        'Cache-Control': 'no-store',
        'Access-Control-Allow-Origin': '*'
      },
      body: text
    });
  } catch (err) {
    return bad(502, { error: 'proxy_failed', message: String(err) });
  }
}

function bad(code, obj) {
  return response({
    status: code,
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
      'Cache-Control': 'no-store'
    },
    body: JSON.stringify(obj)
  });
}
 

bottom of page