Passed
Push — master ( efcce7...8e01eb )
by Muhammad Dyas
01:31
created

src/helpers/api.ts   A

Complexity

Total Complexity 9
Complexity/F 4.5

Size

Lines of Code 46
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 27
mnd 7
bc 7
fnc 2
dl 0
loc 46
rs 10
bpm 3.5
cpm 4.5
noi 0
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A api.ts ➔ gAuth 0 15 1
B api.ts ➔ callMessageApi 0 26 8
1
import {google} from 'googleapis';
2
3
/**
4
 * Create google api credentials
5
 *
6
 * @returns {object} google.chat
7
 */
8
function gAuth() {
9
  // Use default credentials (service account)
10
  const credentials = new google.auth.GoogleAuth({
11
    // keyFile: path.join(__dirname, '../../tests/creds.json'),
12
    scopes: ['https://www.googleapis.com/auth/chat.bot'],
13
  });
14
  return google.chat({
15
    version: 'v1',
16
    auth: credentials,
17
  });
18
}
19
20
/**
21
 * Call Google API using default credentials (service account)
22
 *
23
 * @param {string} action - request action(create,update,get,delete)
24
 * @param {object} request - request body
25
 * @returns {object} Response from google api
26
 */
27
export async function callMessageApi(action: string, request: object) {
28
  const chatApi = gAuth();
29
  let response;
30
31
  try {
32
    if (action === 'create') {
33
      response = await chatApi.spaces.messages.create(request);
34
    } else if (action === 'update') {
35
      response = await chatApi.spaces.messages.update(request);
36
    }
37
  } catch (error) {
38
    // @ts-ignore: all error should have this method
39
    const errorMessage = error.message ?? error.toString() ?? 'Unknown error';
40
    console.error('Error:', action, JSON.stringify(request), response, errorMessage);
41
    throw new Error(errorMessage);
42
  }
43
44
  return response;
45
}
46