@or-sdk/flows 0.27.0-beta.427.0 → 0.27.1-beta.531.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Flows.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { Base, List } from '@or-sdk/base';
2
- import { Flow, StepTemplateRaw } from '@or-sdk/deployer';
3
- import _ from 'lodash';
4
- import {v4 as uuidV4} from 'uuid';
5
- import { SERVICE_KEY } from './constants';
6
- import { FlowsConfig, ListFlowsParams, StepTemplateToDelete, ActivateFlowParams, DeactivageFlowParams } from './types';
7
- import { deleteUnusedStepTemplates, listUnusedStepTemplates } from './utils';
1
+ import { List, makeList } from '@or-sdk/base';
2
+ import { DataHub, GraphqlResponseCheckExecution, GraphqlResponse, GraphqlResponseDelete, OperationNames } from '@or-sdk/data-hub';
3
+ import { Deployer, Flow, PollingResultActivateSuccess, PollingResultDeactivateSuccess, StepTemplateRaw } from '@or-sdk/deployer';
4
+ import { FlowsConfig, FlowListResponse, ListFlowsParams, StepTemplateToDelete } from './types';
5
+ import { QUERY_DELETE, ENTITY_NAME } from './constants';
6
+ import { Tags, Taggable, filterTagIds, addTagsIds, removeTagIds } from '@or-sdk/tags';
7
+ import { listUnusedStepTemplates, deleteUnusedStepTemplates } from './utils';
8
8
 
9
9
  /**
10
10
  * OneReach Flows service client
@@ -13,10 +13,10 @@ import { deleteUnusedStepTemplates, listUnusedStepTemplates } from './utils';
13
13
  * $ npm i @or-sdk/flows
14
14
  * ```
15
15
  */
16
- export class Flows extends Base {
17
- // private readonly dataHub: DataHub;
18
- // private readonly deployer: Deployer;
19
- // private readonly tags: Tags;
16
+ export class Flows implements Taggable<Flow> {
17
+ private readonly dataHub: DataHub;
18
+ private readonly deployer: Deployer;
19
+ private readonly tags: Tags;
20
20
 
21
21
  /**
22
22
  * ```typescript
@@ -25,45 +25,35 @@ export class Flows extends Base {
25
25
  * await flows.init();
26
26
  * ```
27
27
  */
28
- sdkApiUrl?: string;
29
- deployerUrl?: string;
30
28
  constructor(params: FlowsConfig) {
31
- const { discoveryUrl, token, accountId, dataHub2Url, deployerUrl, sdkApiUrl } = params;
32
- super({
29
+ const { discoveryUrl, token, accountId, dataHubUrl, deployerUrl } = params;
30
+
31
+ this.dataHub = new DataHub({
32
+ token,
33
+ discoveryUrl,
34
+ accountId,
35
+ dataHubUrl,
36
+ });
37
+ this.deployer = new Deployer({
33
38
  token,
34
39
  discoveryUrl,
35
- serviceKey: SERVICE_KEY,
36
40
  accountId,
37
- serviceUrl: dataHub2Url,
41
+ deployerUrl,
42
+ });
43
+ this.tags = new Tags({
44
+ token,
45
+ discoveryUrl,
46
+ accountId,
47
+ dataHubUrl,
38
48
  });
39
- this.deployerUrl = deployerUrl;
40
- this.sdkApiUrl = sdkApiUrl;
41
- // this.dataHub = new DataHub({
42
- // token,
43
- // discoveryUrl,
44
- // accountId,
45
- // dataHubUrl,
46
- // });
47
- // this.deployer = new Deployer({
48
- // token,
49
- // discoveryUrl,
50
- // accountId,
51
- // deployerUrl,
52
- // });
53
- // this.tags = new Tags({
54
- // token,
55
- // discoveryUrl,
56
- // accountId,
57
- // dataHubUrl,
58
- // });
59
49
  }
60
50
 
61
51
  async init() {
62
- // await Promise.all([
63
- // this.dataHub.init(),
64
- // this.deployer.init(),
65
- // this.tags.init(),
66
- // ]);
52
+ await Promise.all([
53
+ this.dataHub.init(),
54
+ this.deployer.init(),
55
+ this.tags.init(),
56
+ ]);
67
57
  }
68
58
 
69
59
  /**
@@ -74,169 +64,73 @@ export class Flows extends Base {
74
64
  * const flowsList = await flows.listFlows('bot-id');
75
65
  * ```
76
66
  */
67
+ public async listFlows(botId?: string, params?: ListFlowsParams): Promise<List<Flow>> {
68
+ const requestParams = {
69
+ // defaults
70
+ includeDeleted: false,
71
+ includeExisting: true,
72
+ projection: [
73
+ 'id',
74
+ 'version',
75
+ 'botId',
76
+ 'data.label',
77
+ 'data.color',
78
+ 'data.description',
79
+ 'data.isHidden',
80
+ 'tags',
81
+ 'dateModified',
82
+ ],
83
+
84
+ // overrides
85
+ ...params,
86
+ };
77
87
 
78
- /**
79
- * Delete flow
80
- * ```typescript
81
- * const result = await flows.deleteFlow(flowSource, flowAlias);
82
- * ```
83
- */
84
- async deleteFlow(flow: {id: string;}, flowAlias = 'dev', temporarily = true) {
85
- return this.callApiV2({
86
- route: `/flows/${flow.id}`,
87
- data: {
88
- flowAlias,
89
- temporarily,
90
- },
91
- method: 'delete',
92
- });
93
- }
94
-
95
- /**
96
- * Recover deleted flow
97
- * ```typescript
98
- * const result = await flows.recoverFlow(flowSource);
99
- * ```
100
- */
101
- async recoverFlow(flow: {id: string;}) {
102
- return this.callApiV2({
103
- route: `/flows/${flow.id}`,
104
- method: 'patch',
105
- });
106
- }
107
-
108
- /**
109
- * Get flow by id
110
- * ```typescript
111
- * const result = await flows.getFlowById(id, projection, sandbox);
112
- * ```
113
- */
114
- async getFlowById(id: string, projection?: string[], sandbox = false): Promise<Flow> {
115
- return this.callApiV2({
116
- route: `/flows/${id}`,
117
- params: {
118
- projection,
119
- sandbox,
120
- },
121
- });
122
- }
88
+ const route = `/v2/${this.dataHub.currentAccountId ? this.dataHub.currentAccountId : 'current'}/flows`;
123
89
 
124
- /**
125
- * Get flows
126
- * ```typescript
127
- * const result = await flows.getFlows({query, projection, includeDeleted, includeExisting, sandbox, limit,offset});
128
- * ```
129
- */
130
- async getFlows({ query = {}, projection, includeDeleted = false, includeExisting = true, sandbox = false, limit, offset }: ListFlowsParams = {}): Promise<List<Flow>> {
131
- if (typeof query.id === 'string') query.id = query.id.split('.');
132
- if (includeDeleted && !includeExisting) query.isDeleted = true;
133
- if (!includeDeleted && includeExisting) query.isDeleted = false;
134
- return this.callApiV2({
135
- route: '/flows',
136
- params: {
137
- projection,
138
- query,
139
- sandbox,
140
- limit,
141
- offset,
142
- },
143
- });
144
- }
145
- /**
146
- * Get flow events
147
- * ```typescript
148
- * const result = await flows.getFlowEvents({flowId, alias});
149
- * ```
150
- */
151
- async getFlowEvents({ flowId, alias = 'prod' }: {flowId: string; alias: string;}) {
152
- return this.callApiV2({
153
- url: this.sdkApiUrl,
154
- route: `${this.sdkApiUrl}/event-manager/get-flow-events/${flowId}/${alias}`,
155
- });
156
- }
90
+ let result: FlowListResponse;
91
+ let flowList: Flow[] = [];
92
+ const query: { botId?: string; last?: string; } = { botId: botId ? botId : undefined };
93
+ const projection = JSON.stringify(requestParams.projection);
157
94
 
158
- /**
159
- * Get trigger flows
160
- * ```typescript
161
- * const result = await flows.getTriggerFlows(triggers);
162
- * ```
163
- */
164
- async getTriggerFlows(triggers = []) {
165
- return this.callApiV2({
166
- url: this.sdkApiUrl,
167
- route: `${this.sdkApiUrl}event-manager/get-trigger-flows`,
168
- data: { triggers },
169
- method: 'post',
170
- });
95
+ do {
96
+ result = await this.dataHub.makeRequest({
97
+ method: 'GET',
98
+ route,
99
+ params: {
100
+ includeDeleted: requestParams.includeDeleted,
101
+ includeExisting: requestParams.includeExisting,
102
+ projection,
103
+ query: JSON.stringify(query),
104
+ },
105
+ });
171
106
 
172
- }
107
+ flowList = [...flowList, ...result.items];
108
+ query.last = result.last;
173
109
 
174
- /**
175
- * List versions
176
- * ```typescript
177
- * const result = await flows.listVersions({flowId, botId});
178
- * ```
179
- */
180
- async listVersions(query: {flowId?: string; botId?: string;version?: string;}): Promise<any[]> {
181
- return this.callApiV2({
182
- route: '/flows/versions',
183
- params: { query },
184
- });
185
- }
110
+ } while (result.last);
186
111
 
187
- /**
188
- * Get version
189
- * ```typescript
190
- * const result = await flows.getVersion({flowId, version});
191
- * ```
192
- */
193
- async getVersion(params: {flowId: string; version: string;}) {
194
- const data = await this.listVersions(params);
195
- return data[0];
112
+ return makeList<Flow>(flowList);
196
113
  }
197
114
 
198
115
  /**
199
- * List flow versions by bot id
116
+ * Get flow
200
117
  * ```typescript
201
- * const result = await flows.listFlowVersionsByBotId({botId});
118
+ * const flow = await flows.getFlow('flow-id');
202
119
  * ```
203
120
  */
204
- async listFlowVersionsByBotId(params: { botId: string; }) {
205
- return this.listVersions(params);
206
- }
121
+ public async getFlow(id: string): Promise<Flow> {
122
+ const route = `/v2/${this.dataHub.currentAccountId ? this.dataHub.currentAccountId : 'current'}/flow/${id}`;
207
123
 
208
- /**
209
- * Load flow logs
210
- * ```typescript
211
- * const result = await flows.loadLogs({flowId, next, startTime, endTime, limit, filter, relativeTime});
212
- * ```
213
- */
214
- async loadLogs(params: { flowId: string; next: string; startTime: number; endTime: number; limit: number; filter: string; relativeTime: boolean; }) {
215
- const { flowId, next, startTime, endTime, limit, filter, relativeTime } = params;
216
- const queryParams: {[key: string]: any;} = { skipOriginal: true };
124
+ const params = {
125
+ includeDeleted: false,
126
+ includeExisting: true,
127
+ sandbox: false,
128
+ };
217
129
 
218
- if (next) {
219
- queryParams.next = next;
220
- }
221
- if (startTime) {
222
- queryParams.start = startTime;
223
- }
224
- if (endTime) {
225
- queryParams.end = endTime;
226
- }
227
- if (limit) {
228
- queryParams.limit = limit;
229
- }
230
- if (filter) {
231
- queryParams.filter = filter;
232
- }
233
- if (relativeTime) {
234
- queryParams.relativeTime = relativeTime;
235
- }
236
- return this.callApiV2({
237
- url: this.deployerUrl,
238
- route: `/flows/${flowId}/logs`,
239
- params: queryParams,
130
+ return await this.dataHub.makeRequest<Flow>({
131
+ method: 'GET',
132
+ route,
133
+ params,
240
134
  });
241
135
  }
242
136
 
@@ -245,209 +139,60 @@ export class Flows extends Base {
245
139
  *
246
140
  * If source contains existing id - existing flow will be updated
247
141
  * ```typescript
248
- * const savedFlow = await flows.saveFlow(flowSource, { previousVersion });
249
- * ```
250
- */
251
- async saveFlow(flow: Flow, { previousVersion }: {previousVersion?: string;} = {}) {
252
- flow.id = flow.id || 'new';
253
- const { id, version } = await this.callApiV2({
254
- route: `/flows/${flow.id}`,
255
- data: {
256
- flow,
257
- previousVersion,
258
- },
259
- method: 'post',
260
- });
261
- return {
262
- ...flow,
263
- id,
264
- version,
265
- };
266
- }
267
-
268
- /**
269
- * Get flows by bot id
270
- *
271
- * ```typescript
272
- * const flows = await flows.getFlowsByBotId(botId, projection);
142
+ * const savedFlow = await flows.saveFlow(flowSource);
273
143
  * ```
274
144
  */
275
- getFlowsByBotId(botId: string, projection: string[]) {
276
- return this.getFlows({
277
- query: { botId },
278
- projection,
279
- });
280
- }
145
+ public async saveFlow(source: Flow): Promise<Flow> {
146
+ const route = `/v2/${this.dataHub.currentAccountId ? this.dataHub.currentAccountId : 'current'}/flow/${source.id ? source.id : 'new'}`;
281
147
 
282
- /**
283
- * Get remote data outs by bot id
284
- *
285
- * ```typescript
286
- * const data = await flows.getRemoteDataOutsByBotId(id);
287
- * ```
288
- */
289
- async getRemoteDataOutsByBotId(id: string) {
290
- const flows: any = await this.getFlows({
291
- query: {
292
- botId: id,
293
- isDeleted: false,
294
- },
295
- projection: ['id', 'data.label'],
296
- });
148
+ const data = {
149
+ flow: source,
150
+ previousVersion: source.id ? source.version : undefined,
151
+ };
297
152
 
298
- const dataOuts = await this.callApiV2({
299
- route: 'flows/data-outs',
300
- params: {
301
- query: {
302
- type: {
303
- not: 'session',
304
- ne: null,
305
- },
306
- name: { ne: null },
307
- botId: id,
308
- flowId: flows.map((flow: {id: string;}) => flow.id),
309
- },
310
- },
153
+ return await this.dataHub.makeRequest<Flow>({
154
+ method: 'POST',
155
+ route,
156
+ data,
311
157
  });
312
-
313
- return _.reduce(flows, (acc: any, flow: any) => {
314
- const flowLabel = _.get(flow, 'data.label', 'No name flow');
315
- acc[flow.id] = _.map(dataOuts as any, (dataOut: any) => ({
316
- ...dataOut,
317
- flowLabel,
318
- }));
319
- return acc;
320
- }, {});
321
158
  }
322
159
 
323
160
  /**
324
- * Get empty step
325
- *
161
+ * Delete flow
326
162
  * ```typescript
327
- * const data = await flows.constructor.getEmptyStep(id);
163
+ * const result = await flows.deleteFlow(flowSource, flowAlias);
328
164
  * ```
329
165
  */
330
- static getEmptyStep(stepId?: string) {
331
- return {
332
- id: stepId || uuidV4(),
333
- icon: 'add',
334
- iconType: 'default',
335
- iconUrl: '',
336
- shape: 'empty',
337
- type: 'empty',
338
- pinLabel: true,
339
- stepInputData: {},
340
- };
341
- }
166
+ public async deleteFlow(source: Flow, flowAlias = 'dev'): Promise<GraphqlResponseCheckExecution> {
167
+ if (this.dataHub.isCrossAccount) {
168
+ throw Error('Cross-account deleting is not implemented.');
169
+ }
342
170
 
343
- /**
344
- * Get empty flow
345
- *
346
- * ```typescript
347
- * const data = await flows.constructor.getEmptyFlow(botId);
348
- * ```
349
- */
350
- static getEmptyFlow(botId: string): any {
351
- const defaultLambdaMemorySize = 1024;
352
- const defaultLambdaTimeout = 30;
353
- return {
354
- botId,
171
+ const variables = {
172
+ entity: ENTITY_NAME,
355
173
  data: {
356
- label: '',
357
- description: '',
358
- deploy: {
359
- memory: defaultLambdaMemorySize,
360
- timeout: defaultLambdaTimeout,
361
- role: 'USER',
362
- },
363
- meta: {},
364
- color: null,
365
- categories: null,
366
- annotations: null,
367
- stepTemplates: [],
368
- trees: {
369
- main: {
370
- position: {
371
- x: 0,
372
- y: 0,
373
- },
374
- steps: [this.getEmptyStep()],
375
- },
376
- },
174
+ id: source.id,
175
+ flowAlias,
176
+ subscribe: true,
177
+ role: source.data.deploy.role,
377
178
  },
378
179
  };
379
- }
380
-
381
- /**
382
- * Get new flow
383
- *
384
- * ```typescript
385
- * const data = await flows.constructor.getNewFlow(botId, flowTemplate);
386
- * ```
387
- */
388
- static async getNewFlow(botId: string, flowTemplate: any) {
389
- const flow = this.getEmptyFlow(botId);
390
- const template = _.omit(flowTemplate, ['id', 'botId', 'dateCreated', 'dateModified', 'version']);
391
180
 
392
- // if template has any steps then remove default empty step
393
- // or leave it otherwise
394
- flow.data.steps = _.get(template, 'data.steps.length') > 0 ? [] : flow.data.steps;
395
-
396
- // merge step with flow template
397
- return _.merge(flow, template);
398
- }
181
+ const operationName = this.dataHub.getOperationName(OperationNames.DELETE_TEMPORARILY);
399
182
 
183
+ const data = {
184
+ operationName,
185
+ query: QUERY_DELETE,
186
+ variables,
187
+ };
400
188
 
401
- public async listFlows(botId?: string, params: ListFlowsParams = {}): Promise<List<Flow>> {
402
- return this.getFlows({
403
- ...params,
404
- query: { botId },
189
+ const result = await this.dataHub.makeRequest<GraphqlResponse<void>>({
190
+ method: 'POST',
191
+ route: '/graphql',
192
+ data,
405
193
  });
406
- }
407
-
408
- /**
409
- * Get flow
410
- * ```typescript
411
- * const flow = await flows.getFlow('flow-id');
412
- * ```
413
- */
414
- public async getFlow(id: string): Promise<Flow> {
415
- return this.getFlowById(id);
416
- }
417
-
418
- private get deployUrl() {
419
- return this.targetAccountId ? `${this.deployerUrl}/accounts/${this.targetAccountId}/flows/deploy` : `${this.deployerUrl}/flows/deploy`;
420
- }
421
-
422
194
 
423
- private get checkUrl() {
424
- return this.targetAccountId ? `${this.deployerUrl}/accounts/${this.targetAccountId}/flows/check` : `${this.deployerUrl}/flows/check`;
425
- }
426
-
427
- private async _pollResult(flowId: string, requestId: string, headers?: any, progresCallback?: any) {
428
- let counter = 0;
429
-
430
- do {
431
- counter++;
432
- await new Promise(r => setTimeout(r, 1000));
433
-
434
- const result: any = await this.callApiV2({
435
- url: `${this.checkUrl}`,
436
- route: `/${flowId}/${requestId}`,
437
- });
438
- if (_.isFunction(progresCallback)) {
439
- progresCallback(result);
440
- }
441
- if (result.status !== 'pending') {
442
- if (result.errorData) {
443
- throw result;
444
- }
445
-
446
- return result;
447
- }
448
- } while (counter < 100);
449
-
450
- throw new Error('Activation duration is too long');
195
+ return this.dataHub.subscribe((result.data[operationName] as GraphqlResponseDelete).requestId);
451
196
  }
452
197
 
453
198
  /**
@@ -456,23 +201,8 @@ export class Flows extends Base {
456
201
  * const triggerList = await flows.activateFlow(flowSource, false);
457
202
  * ```
458
203
  */
459
-
460
- async activateFlow(flow: ActivateFlowParams, progresCallback: any) {
461
- const flowAlias = `v-${Date.now()}`;
462
-
463
- const { requestId } = await this.callApiV2({
464
- url: this.deployUrl,
465
- route: '',
466
- method: 'post',
467
- data: {
468
- flowId: flow.id,
469
- flowAlias,
470
- interactiveDebug: flow.interactiveDebug,
471
- role: _.get(flow, 'data.deploy.role'),
472
- },
473
- });
474
-
475
- return this._pollResult(flow.id, requestId, null, progresCallback);
204
+ public async activateFlow(source: Flow, interactiveDebug = false): Promise<PollingResultActivateSuccess> {
205
+ return this.deployer.activateFlow(source, interactiveDebug);
476
206
  }
477
207
 
478
208
  /**
@@ -481,46 +211,31 @@ export class Flows extends Base {
481
211
  * const deactivatedFlowList = await flows.deactivateFlow(flowSource, 'flowAlias', false);
482
212
  * ```
483
213
  */
484
- async deactivateFlow(flow: DeactivageFlowParams, flowAlias: string, deleteLambda = false) {
485
- const { requestId } = await this.callApiV2({
486
- url: this.deployUrl,
487
- route: '',
488
- method: 'delete',
489
- data: {
490
- flow: {
491
- id: flow.id,
492
- },
493
- flowAlias,
494
- role: _.get(flow, 'data.deploy.role'),
495
- deleteLambda,
496
- },
497
- });
498
-
499
- return this._pollResult(flow.id, requestId);
214
+ public async deactivateFlow(source: Flow, flowAlias: string, deleteLambda = false): Promise<PollingResultDeactivateSuccess> {
215
+ return this.deployer.deactivateFlow(source, flowAlias, deleteLambda);
500
216
  }
501
217
 
502
-
503
218
  /**
504
219
  * Add tags
505
220
  * ```typescript
506
221
  * const flow = await flows.addTags(flowSource, tagIdsArr);
507
222
  * ```
508
223
  */
509
- // public async addTags(source: Flow, tagNames: string[]): Promise<Flow> {
510
- // const tags = await this.tags.getMultipleTagsByName(tagNames, true);
511
- // const tagIds = tags.map(tag => tag.id!);
224
+ public async addTags(source: Flow, tagNames: string[]): Promise<Flow> {
225
+ const tags = await this.tags.getMultipleTagsByName(tagNames, true);
226
+ const tagIds = tags.map(tag => tag.id!);
512
227
 
513
- // const { newIds } = filterTagIds(source.tags, tagIds);
228
+ const { newIds } = filterTagIds(source.tags, tagIds);
514
229
 
515
- // if (!newIds.length) {
516
- // throw Error('No tags to add.');
517
- // }
230
+ if (!newIds.length) {
231
+ throw Error('No tags to add.');
232
+ }
518
233
 
519
- // return this.saveFlow({
520
- // ...source,
521
- // tags: addTagsIds(source.tags, newIds),
522
- // });
523
- // }
234
+ return this.saveFlow({
235
+ ...source,
236
+ tags: addTagsIds(source.tags, newIds),
237
+ });
238
+ }
524
239
 
525
240
  /**
526
241
  * Remove tags
@@ -528,21 +243,21 @@ export class Flows extends Base {
528
243
  * const flow = await flows.removeTags(flowSource, tagIdsArr);
529
244
  * ```
530
245
  */
531
- // public async removeTags(source: Flow, tagNames: string[]): Promise<Flow> {
532
- // const tags = await this.tags.getMultipleTagsByName(tagNames);
533
- // const tagIds = tags.map(tag => tag.id!);
246
+ public async removeTags(source: Flow, tagNames: string[]): Promise<Flow> {
247
+ const tags = await this.tags.getMultipleTagsByName(tagNames);
248
+ const tagIds = tags.map(tag => tag.id!);
534
249
 
535
- // const { existingIds } = filterTagIds(source.tags, tagIds);
250
+ const { existingIds } = filterTagIds(source.tags, tagIds);
536
251
 
537
- // if (!existingIds.length) {
538
- // throw Error('No tags to remove.');
539
- // }
252
+ if (!existingIds.length) {
253
+ throw Error('No tags to remove.');
254
+ }
540
255
 
541
- // return this.saveFlow({
542
- // ...source,
543
- // tags: removeTagIds(source.tags, existingIds),
544
- // });
545
- // }
256
+ return this.saveFlow({
257
+ ...source,
258
+ tags: removeTagIds(source.tags, existingIds),
259
+ });
260
+ }
546
261
 
547
262
  /**
548
263
  * List unused step templates from flow source
package/src/constants.ts CHANGED
@@ -1,2 +1,12 @@
1
- export const SERVICE_KEY = 'datahub2';
1
+ export { DATA_HUB_SERVICE_KEY } from '@or-sdk/data-hub';
2
+ export { DEPLOYER_SERVICE_KEY } from '@or-sdk/deployer';
2
3
 
4
+ export const QUERY_DELETE = `mutation deleteTemporarily($entity: EntityType!, $data: DeleteInput!) {
5
+ deleteTemporarily(entity: $entity, data: $data) {
6
+ ... on AsyncRequest {
7
+ requestId
8
+ }
9
+ }
10
+ }`;
11
+
12
+ export const ENTITY_NAME = 'FLOW';