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

src/helpers/task.ts   A

Complexity

Total Complexity 3
Complexity/F 3

Size

Lines of Code 39
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 32
mnd 2
bc 2
fnc 1
dl 0
loc 39
rs 10
bpm 2
cpm 3
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A task.ts ➔ createTask 0 33 3
1
import {CloudTasksClient} from '@google-cloud/tasks';
2
import {google} from '@google-cloud/tasks/build/protos/protos';
3
4
const client = new CloudTasksClient();
5
6
export async function createTask(payload: string, scheduleInSeconds?: number) {
7
  const project = process.env.GCP_PROJECT;
8
  const queue = process.env.QUEUE_NAME;
9
  const location = process.env.FUNCTION_REGION;
10
  if (!project || !queue || !location) {
11
    throw new Error('Missing required environment variables');
12
  }
13
  const url = `https://${location}-${project}.cloudfunctions.net/app`;
14
  // Construct the fully qualified queue name.
15
  const parent = client.queuePath(project, location, queue);
16
17
  const task: google.cloud.tasks.v2.ITask = {
18
    httpRequest: {
19
      headers: {
20
        'Content-Type': 'application/json', // Set content type to ensure compatibility your application's request parsing
21
      }, httpMethod: 'POST', url,
22
    },
23
  };
24
25
  task.httpRequest!.body = Buffer.from(payload).toString('base64');
26
27
  if (scheduleInSeconds) {
28
    // The time when the task is scheduled to be attempted.
29
    task.scheduleTime = {
30
      seconds: scheduleInSeconds / 1000,
31
    };
32
  }
33
34
  const request: google.cloud.tasks.v2.ICreateTaskRequest = {parent: parent, task: task};
35
  const [response]= await client.createTask(request);
36
  console.log(`Created task ${response.name}`);
37
  return response;
38
}
39