1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const tasks_1 = require("@google-cloud/tasks");
|
4 | const node_fetch_1 = require("node-fetch");
|
5 | const logging_1 = require("./logging");
|
6 | class TaskQueue {
|
7 | constructor(configurationProvider, queueName) {
|
8 | this.configurationProvider = configurationProvider;
|
9 | this.queueName = queueName;
|
10 | this.taskLogger = logging_1.createLogger('task-queue');
|
11 | }
|
12 | async enqueue(taskName, payload = {}) {
|
13 | if (this.configurationProvider.environment === 'development') {
|
14 | await this.localQueue(taskName, payload);
|
15 | }
|
16 | else {
|
17 | await this.appEngineQueue(taskName, payload);
|
18 | }
|
19 | }
|
20 | async appEngineQueue(taskName, payload = {}) {
|
21 | const client = new tasks_1.default.v2beta3.CloudTasksClient();
|
22 | const projectId = this.configurationProvider.projectId;
|
23 | const location = this.configurationProvider.location;
|
24 | const body = JSON.stringify(payload);
|
25 | const requestPayload = Buffer.from(body).toString('base64');
|
26 | const parent = `projects/${projectId}/locations/${location}/queues/${this.queueName}`;
|
27 | const task = {
|
28 | appEngineHttpRequest: {
|
29 | relativeUri: `/tasks/${taskName}`,
|
30 | headers: {
|
31 | 'Content-Type': 'application/json',
|
32 | },
|
33 | body: requestPayload,
|
34 | httpMethod: 'POST',
|
35 | },
|
36 | };
|
37 | await client.createTask({
|
38 | parent,
|
39 | task,
|
40 | });
|
41 | }
|
42 | async localQueue(taskName, payload = {}) {
|
43 | const endpoint = `${this.configurationProvider.host}/tasks/${taskName}`;
|
44 | this.taskLogger.info(`Dispatching local task to ${endpoint}`);
|
45 | const result = await node_fetch_1.default(endpoint, {
|
46 | method: 'POST',
|
47 | body: JSON.stringify(payload),
|
48 | headers: {
|
49 | 'content-type': 'application/json',
|
50 | 'x-appengine-taskname': taskName,
|
51 | },
|
52 | });
|
53 | if (!result.ok) {
|
54 | throw new Error(`Task failed to execute - status ${result.status}: ${await result.text()}`);
|
55 | }
|
56 | }
|
57 | }
|
58 | exports.TaskQueue = TaskQueue;
|
59 |
|
\ | No newline at end of file |