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

src/handlers/TaskHandler.ts   A

Complexity

Total Complexity 11
Complexity/F 3.67

Size

Lines of Code 54
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 42
mnd 8
bc 8
fnc 3
dl 0
loc 54
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 16 5
A TaskHandler.updatePollMessage 0 10 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
        currentState.closedBy = 'scheduled auto-close';
21
        const apiResponse = await this.updatePollMessage(currentState);
22
        if (apiResponse?.status !== 200) {
23
          throw new Error('Error when closing message');
24
        }
25
        break;
26
      default:
27
        console.log('unknown task');
28
    }
29
  }
30
31
  async getStateFromMessageId(): Promise<PollState> {
32
    const request = {
33
      name: this.event.id,
34
    };
35
    const apiResponse = await callMessageApi('get', request);
36
    const currentState = getStateFromCardName(apiResponse.data!.cardsV2?.[0].card ?? {});
37
    if (!currentState) {
38
      throw new Error('State not found');
39
    }
40
    return JSON.parse(currentState) as PollState;
41
  }
42
43
  async updatePollMessage(currentState: PollState) {
44
    const localeTimezone = {locale: 'en', offset: 0, id: 'UTC'};
45
    const cardMessage = new PollCard(currentState, localeTimezone).createMessage();
46
    const request = {
47
      name: this.event.id,
48
      requestBody: cardMessage,
49
      updateMask: 'cardsV2',
50
    };
51
    return await callMessageApi('update', request);
52
  }
53
}
54