Passed
Pull Request — master (#19)
by Muhammad Dyas
01:35
created

src/handlers/TaskHandler.ts   A

Complexity

Total Complexity 11
Complexity/F 3.67

Size

Lines of Code 52
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 40
mnd 8
bc 8
fnc 3
dl 0
loc 52
rs 10
bpm 2.6666
cpm 3.6666
noi 0
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A TaskHandler.getStateFromMessageId 0 11 5
A TaskHandler.process 0 15 5
A TaskHandler.updatePollMessage 0 9 1
1
import {PollState, taskEvent} from '../helpers/interfaces';
2
import {callMessageApi} from '../helpers/api';
3
import {getStateFromCardName} from '../helpers/state';
4
import PollCard from '../cards/PollCard';
5
6
export default class TaskHandler {
7
  event: taskEvent;
8
9
  public constructor(event: taskEvent) {
10
    this.event = event;
11
  }
12
13
  async process(): Promise<void> {
14
    switch (this.event.action) {
15
      case 'close_poll':
16
        const currentState = await this.getStateFromMessageId();
17
        if (!currentState.closedTime || currentState.closedTime > Date.now()) {
18
          currentState.closedTime = Date.now();
19
        }
20
        const apiResponse = await this.updatePollMessage(currentState);
21
        if (apiResponse?.status !== 200) {
22
          throw new Error('Error when closing message');
23
        }
24
        break;
25
      default:
26
        console.log('unknown task');
27
    }
28
  }
29
30
  async getStateFromMessageId(): Promise<PollState> {
31
    const request = {
32
      name: this.event.id,
33
    };
34
    const apiResponse = await callMessageApi('get', request);
35
    const currentState = getStateFromCardName(apiResponse.data!.cardsV2?.[0].card ?? {});
36
    if (!currentState) {
37
      throw new Error('State not found');
38
    }
39
    return JSON.parse(currentState) as PollState;
40
  }
41
42
  async updatePollMessage(currentState: PollState) {
43
    const cardMessage = new PollCard(currentState).createMessage();
44
    const request = {
45
      name: this.event.id,
46
      requestBody: cardMessage,
47
      updateMask: 'cardsV2',
48
    };
49
    return await callMessageApi('update', request);
50
  }
51
}
52