export const url = "https://networkheaven.net";

export interface ReqParams {
  method: string,
  body?: string,
}

export async function post( endpoint: string, body: Object ) {
  return await req( endpoint, {
    method: "POST",
    body: JSON.stringify( body ),
  } );
}

export async function req( endpoint: string, params: ReqParams ) {
  const res = await fetch( `${url}/${endpoint}`, {
    method: params.method,
    headers: {
      "Content-Type": "application/json",
    },
    body: params.body,
  } );

  if( !res.ok ) {
    let json = null;
    try {
      json = await res.json();
    } catch( e: any ) {
      throw new Error( "error contacting server" );
    }

    throw new Error( json.msg );
  }

  const json = await res.json();
  if( json.status != 'ok' )
    throw new Error( json.msg );
  return json;
}
