GenesysService.ts 2.38 KB
Newer Older
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
// import { ServerInfo } from 'model/serverinfo.model';
// import { SERVER_INFO_URL } from 'constants/apiURLS';
import axios from 'axios';
import authenticatedRequest from 'utilities/requestUtils';
import * as _ from 'lodash';

import {Page} from 'model/common.model';

const API_PREFIX = '/api/genesys';

export class GenesysService {
  private static accessToken: any = null;

  public static login(): Promise<any> {
    if (GenesysService.accessToken === null || GenesysService.accessToken.expireTimestamp < Date.now()) {
      return axios.post(`${API_PREFIX}/oauth/token`, null, {
        params: {
          grant_type: 'client_credentials',
        },
      })
        .then(({ data }) => {
          data.expireTimestamp = Date.now() + (data.expires_in - 10) * 1000;
          return GenesysService.accessToken = data;
        });
    } else {
      return Promise.resolve(GenesysService.accessToken);
    }
  }

  public static listAccessions(filters: object, page: number = 0, results: number = 50): Promise<Page<object>> {

    const flatFilters = genesysFlatten('', renameFilters(filters), {});
    // console.log(`Flatfilters ${JSON.stringify(flatFilters)}`, filters, flatFilters);

    return GenesysService.login()
      .then((token) => {
        // console.log('Genesys token', token);
        return authenticatedRequest(token.access_token, {
          url: `${API_PREFIX}/v0/acn/filter?p=${page}&l=${results}`,
          method: 'POST',
          data: {
            ...flatFilters,
          },
        });
      })
        .then(({ data }) => new Page<object>(data));
47
        // TODO catch 403 -- reauth
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
  }
}

const renameFilters = (filters: any) => {
  const renamed: any = { ...filters };
  renamed.crops = renamed.crop;
  delete renamed.crop;
  return renamed;
};

/**
 * Genesys PGR uses a semi-flat JSON structure, with arrays and literals as values:
 * { institute: { code: [ 'NGA039' ] } } --> { 'institute.code': [ 'NGA039' ] }
 */
const genesysFlatten = (prefix: string, obj: object, result: any) => {
  for (const k of Object.keys(obj)) {
    const val = obj[k];
    // console.log(`${k} = ${val} typeof ${typeof val}`);
    if (_.isObject(val)) {
      if (_.isArray(val) && val.length > 0) {
        result[`${prefix}${k}`] = val;
      } else {
        genesysFlatten(`${prefix}${k}.`, val, result);
      }
    } else if (val !== null) {
      result[`${prefix}${k}`] = val;
    }
  }
  return result;
};