Completed
Push — master ( 605e3d...3de0bb )
by Muhammad Dyas
14s queued 13s
created

api.ts ➔ callMessageApi   C

Complexity

Conditions 10

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 32
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Complexity   

Complexity

Complex classes like api.ts ➔ callMessageApi often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
    } else if (action === 'get') {
37
      response = await chatApi.spaces.messages.get(request);
38
    }
39
  } catch (error) {
40
    // @ts-ignore: all error should have this method
41
    const errorMessage = error.message ?? error.toString() ?? 'Unknown error';
42
    console.error('Error:', action, JSON.stringify(request), response, errorMessage);
43
    throw new Error(errorMessage);
44
  }
45
46
  if (!response) {
47
    throw new Error('Empty response');
48
  }
49
50
  return response;
51
}
52