| Total Complexity | 2 |
| Complexity/F | 2 |
| Lines of Code | 37 |
| Function Count | 1 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 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 | // The time when the task is scheduled to be attempted. |
||
| 28 | task.scheduleTime = { |
||
| 29 | seconds: scheduleInSeconds / 1000, |
||
| 30 | }; |
||
| 31 | |||
| 32 | const request: google.cloud.tasks.v2.ICreateTaskRequest = {parent: parent, task: task}; |
||
| 33 | const [response] = await client.createTask(request); |
||
| 34 | console.log(`Created task ${response.name}`); |
||
| 35 | return response; |
||
| 36 | } |
||
| 37 |