summaryrefslogtreecommitdiff
path: root/web/src/api.tsx
blob: 7233d8947b2b032c73d859ea4dfe9e63e6259945 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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;
}