summaryrefslogtreecommitdiff
path: root/moneyjsx/src/api.tsx
blob: 4ca79c219642ec1db3d2cd641e765fd04d350594 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// todo: change this
export const url = "https://api.axonbox.net";
export let models: Model[] = [];

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

export interface Model {
  name: string,
  capabilities: any,
  description: {
    full: string,
    short: string,
  },
  license: string,
  free: number
}

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;
}

export async function updateModels() {
  parseModels();

  try {
    const res = await post( 'models', {} );
    models = res.models as Model[];
    localStorage.setItem( 'models', JSON.stringify( models ) );
  } catch( e: any ) {
    throw new Error( e.message );
  }
}

export function getModelFromName( name: string ) {
  for( let model of models ) {
    if( model.name === name )
      return model;
  }

  return null;
}

/**
 * parses existing models from localStorage
**/
export function parseModels() {
  models = JSON.parse( localStorage.getItem( 'models' ) || '[]' ) as Model[];
}