@contrail/flexplm 1.3.0 → 1.3.1-alpha.56221f6

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.
Files changed (149) hide show
  1. package/lib/cli/commands/compile.d.ts +1 -0
  2. package/lib/cli/commands/compile.js +71 -0
  3. package/lib/cli/commands/compile.spec.d.ts +1 -0
  4. package/lib/cli/commands/compile.spec.js +80 -0
  5. package/lib/cli/commands/create.d.ts +1 -0
  6. package/lib/cli/commands/create.js +75 -0
  7. package/lib/cli/commands/create.spec.d.ts +1 -0
  8. package/lib/cli/commands/create.spec.js +78 -0
  9. package/lib/cli/commands/upload.d.ts +10 -0
  10. package/lib/cli/commands/upload.js +219 -0
  11. package/lib/cli/commands/upload.spec.d.ts +1 -0
  12. package/lib/cli/commands/upload.spec.js +88 -0
  13. package/lib/cli/index.d.ts +2 -0
  14. package/lib/cli/index.js +64 -0
  15. package/lib/cli/index.spec.d.ts +1 -0
  16. package/lib/cli/index.spec.js +79 -0
  17. package/lib/cli/template/mapping-template.ts.template +18 -0
  18. package/lib/entity-processor/base-entity-processor.d.ts +89 -42
  19. package/lib/entity-processor/base-entity-processor.js +438 -385
  20. package/lib/entity-processor/base-entity-processor.spec.d.ts +1 -1
  21. package/lib/entity-processor/base-entity-processor.spec.js +398 -397
  22. package/lib/flexplm-request.d.ts +3 -3
  23. package/lib/flexplm-request.js +34 -34
  24. package/lib/flexplm-utils.d.ts +5 -5
  25. package/lib/flexplm-utils.js +33 -33
  26. package/lib/flexplm-utils.spec.d.ts +1 -1
  27. package/lib/flexplm-utils.spec.js +26 -26
  28. package/lib/index.d.ts +23 -22
  29. package/lib/index.js +39 -38
  30. package/lib/interfaces/interfaces.d.ts +105 -105
  31. package/lib/interfaces/interfaces.js +2 -2
  32. package/lib/interfaces/item-family-changes.d.ts +20 -20
  33. package/lib/interfaces/item-family-changes.js +56 -56
  34. package/lib/interfaces/mapping-file.d.ts +429 -0
  35. package/lib/interfaces/mapping-file.js +2 -0
  36. package/lib/interfaces/publish-change-data.d.ts +19 -19
  37. package/lib/interfaces/publish-change-data.js +32 -32
  38. package/lib/publish/base-process-publish-assortment-callback.d.ts +9 -9
  39. package/lib/publish/base-process-publish-assortment-callback.js +38 -38
  40. package/lib/publish/base-process-publish-assortment.d.ts +118 -93
  41. package/lib/publish/base-process-publish-assortment.js +998 -944
  42. package/lib/publish/base-process-publish-assortment.spec.d.ts +1 -1
  43. package/lib/publish/base-process-publish-assortment.spec.js +1688 -1670
  44. package/lib/publish/mockData.d.ts +1389 -1389
  45. package/lib/publish/mockData.js +4524 -4519
  46. package/lib/transform/identifier-conversion-spec-mockData.js +472 -444
  47. package/lib/transform/identifier-conversion.d.ts +51 -15
  48. package/lib/transform/identifier-conversion.js +248 -212
  49. package/lib/transform/identifier-conversion.spec.d.ts +1 -1
  50. package/lib/transform/identifier-conversion.spec.js +343 -339
  51. package/lib/util/config-defaults.d.ts +8 -8
  52. package/lib/util/config-defaults.js +88 -85
  53. package/lib/util/config-defaults.spec.d.ts +1 -1
  54. package/lib/util/config-defaults.spec.js +302 -293
  55. package/lib/util/data-converter-spec-mockData.js +219 -205
  56. package/lib/util/data-converter.d.ts +136 -39
  57. package/lib/util/data-converter.js +718 -592
  58. package/lib/util/data-converter.spec.d.ts +1 -1
  59. package/lib/util/data-converter.spec.js +906 -904
  60. package/lib/util/error-response-object.d.ts +9 -4
  61. package/lib/util/error-response-object.js +54 -47
  62. package/lib/util/error-response-object.spec.d.ts +1 -1
  63. package/lib/util/error-response-object.spec.js +99 -99
  64. package/lib/util/event-short-message-status.d.ts +19 -19
  65. package/lib/util/event-short-message-status.js +24 -23
  66. package/lib/util/federation.d.ts +15 -15
  67. package/lib/util/federation.js +157 -149
  68. package/lib/util/flexplm-connect.d.ts +29 -22
  69. package/lib/util/flexplm-connect.js +190 -176
  70. package/lib/util/flexplm-connect.spec.d.ts +1 -1
  71. package/lib/util/flexplm-connect.spec.js +88 -88
  72. package/lib/util/logger-config.d.ts +1 -1
  73. package/lib/util/logger-config.js +27 -26
  74. package/lib/util/map-util-spec-mockData.js +219 -205
  75. package/lib/util/map-utils.d.ts +33 -6
  76. package/lib/util/map-utils.js +42 -15
  77. package/lib/util/map-utils.spec.d.ts +1 -1
  78. package/lib/util/map-utils.spec.js +89 -89
  79. package/lib/util/mockData.d.ts +80 -80
  80. package/lib/util/mockData.js +103 -103
  81. package/lib/util/thumbnail-util.d.ts +55 -34
  82. package/lib/util/thumbnail-util.js +242 -215
  83. package/lib/util/thumbnail-util.spec.d.ts +1 -1
  84. package/lib/util/thumbnail-util.spec.js +440 -434
  85. package/lib/util/type-conversion-utils-spec-mockData.js +259 -259
  86. package/lib/util/type-conversion-utils.d.ts +163 -23
  87. package/lib/util/type-conversion-utils.js +408 -265
  88. package/lib/util/type-conversion-utils.spec.d.ts +1 -1
  89. package/lib/util/type-conversion-utils.spec.js +868 -868
  90. package/lib/util/type-defaults.d.ts +74 -16
  91. package/lib/util/type-defaults.js +279 -221
  92. package/lib/util/type-defaults.spec.d.ts +1 -1
  93. package/lib/util/type-defaults.spec.js +516 -516
  94. package/lib/util/type-utils.d.ts +34 -13
  95. package/lib/util/type-utils.js +137 -114
  96. package/lib/util/type-utils.spec.d.ts +1 -1
  97. package/lib/util/type-utils.spec.js +192 -190
  98. package/package.json +21 -6
  99. package/scripts/copy-template.js +10 -0
  100. package/.claude/settings.local.json +0 -8
  101. package/.github/pull_request_template.md +0 -31
  102. package/.github/workflows/flexplm-lib.yml +0 -27
  103. package/.github/workflows/publish-to-npm.yml +0 -124
  104. package/CHANGELOG.md +0 -32
  105. package/publish.bat +0 -5
  106. package/publish.sh +0 -5
  107. package/src/entity-processor/base-entity-processor.spec.ts +0 -460
  108. package/src/entity-processor/base-entity-processor.ts +0 -515
  109. package/src/flexplm-request.ts +0 -28
  110. package/src/flexplm-utils.spec.ts +0 -27
  111. package/src/flexplm-utils.ts +0 -29
  112. package/src/index.ts +0 -22
  113. package/src/interfaces/interfaces.ts +0 -122
  114. package/src/interfaces/item-family-changes.ts +0 -67
  115. package/src/interfaces/publish-change-data.ts +0 -43
  116. package/src/publish/base-process-publish-assortment-callback.ts +0 -50
  117. package/src/publish/base-process-publish-assortment.spec.ts +0 -1992
  118. package/src/publish/base-process-publish-assortment.ts +0 -1134
  119. package/src/publish/mockData.ts +0 -4561
  120. package/src/transform/identifier-conversion-spec-mockData.ts +0 -496
  121. package/src/transform/identifier-conversion.spec.ts +0 -354
  122. package/src/transform/identifier-conversion.ts +0 -282
  123. package/src/util/config-defaults.spec.ts +0 -350
  124. package/src/util/config-defaults.ts +0 -93
  125. package/src/util/data-converter-spec-mockData.ts +0 -231
  126. package/src/util/data-converter.spec.ts +0 -1041
  127. package/src/util/data-converter.ts +0 -762
  128. package/src/util/error-response-object.spec.ts +0 -116
  129. package/src/util/error-response-object.ts +0 -50
  130. package/src/util/event-short-message-status.ts +0 -22
  131. package/src/util/federation.ts +0 -172
  132. package/src/util/flexplm-connect.spec.ts +0 -132
  133. package/src/util/flexplm-connect.ts +0 -208
  134. package/src/util/logger-config.ts +0 -20
  135. package/src/util/map-util-spec-mockData.ts +0 -231
  136. package/src/util/map-utils.spec.ts +0 -103
  137. package/src/util/map-utils.ts +0 -41
  138. package/src/util/mockData.ts +0 -101
  139. package/src/util/thumbnail-util.spec.ts +0 -508
  140. package/src/util/thumbnail-util.ts +0 -272
  141. package/src/util/type-conversion-utils-spec-mockData.ts +0 -271
  142. package/src/util/type-conversion-utils.spec.ts +0 -968
  143. package/src/util/type-conversion-utils.ts +0 -460
  144. package/src/util/type-defaults.spec.ts +0 -669
  145. package/src/util/type-defaults.ts +0 -281
  146. package/src/util/type-utils.spec.ts +0 -227
  147. package/src/util/type-utils.ts +0 -144
  148. package/tsconfig.json +0 -29
  149. package/tslint.json +0 -57
@@ -1,116 +0,0 @@
1
- import { AppActionCallbackStatus } from "@contrail/app-framework";
2
- import { ErrorResponseObject } from "./error-response-object";
3
-
4
- describe('getResponse() Tests', () =>{
5
- it('no error provided', () => {
6
- const e = undefined;
7
-
8
- const response = ErrorResponseObject.getResponse(e);
9
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
10
- expect(response?.output?.message).toMatch('No error provided');
11
- });
12
- it('error with message', () => {
13
- const e = {
14
- message: 'Test'
15
- };
16
-
17
- const response = ErrorResponseObject.getResponse(e);
18
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
19
- expect(response?.output?.message).toMatch('Test');
20
- });
21
-
22
- it('error with details', () => {
23
- const details = {
24
- message: 'Detail Message',
25
- itemType: [
26
- {
27
- message: "Type 'item:product:newBalance:apparel' cannot be assigned to a property with type 'item'."
28
- }]
29
- };
30
- const e = {
31
- message: 'Test',
32
- details
33
-
34
- };
35
-
36
- const response = ErrorResponseObject.getResponse(e);
37
- expect(response).toBeTruthy();
38
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
39
- expect(response.output.message).toMatch('Test');
40
-
41
- const errorDetails = response.output.errorDetails;
42
- expect(errorDetails).toBeTruthy();
43
- expect(errorDetails.message).toMatch('Detail Message');
44
- expect(errorDetails).toHaveProperty('itemType');
45
- });
46
-
47
- it('error with cause', () => {
48
- const cause = {
49
- code: 401,
50
- message: 'cause message'
51
- };
52
- const e = {
53
- message: 'Test',
54
- cause
55
- };
56
-
57
- const response = ErrorResponseObject.getResponse(e);
58
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
59
- expect(response?.output?.message).toMatch('Test');
60
- const resCause = response.output.cause;
61
-
62
- expect(resCause).toBeTruthy();
63
- expect(resCause.code).toBe(401);
64
- expect(resCause.message).toMatch('cause message');
65
-
66
- });
67
-
68
- it('error with code', () => {
69
- const e = {
70
- message: 'Test',
71
- code: 404
72
- };
73
-
74
- const response = ErrorResponseObject.getResponse(e);
75
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
76
- expect(response?.output?.message).toMatch('Test');
77
- expect(response.output.code).toBe(404);
78
- });
79
-
80
- it('error with code', () => {
81
- const e = {
82
- message: 'Test',
83
- name: 'Error'
84
- };
85
-
86
- const response = ErrorResponseObject.getResponse(e);
87
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
88
- expect(response?.output?.message).toMatch('Test');
89
- expect(response.output.errorName).toMatch('Error');
90
- });
91
-
92
- it('error with errno', () => {
93
- const e = {
94
- message: 'Test',
95
- errno: 500
96
- };
97
-
98
- const response = ErrorResponseObject.getResponse(e);
99
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
100
- expect(response?.output?.message).toMatch('Test');
101
- expect(response.output.errno).toBe(500);
102
- });
103
-
104
- it('error with type', () => {
105
- const e = {
106
- message: 'Test',
107
- type: 'system'
108
- };
109
-
110
- const response = ErrorResponseObject.getResponse(e);
111
- expect(response.status).toMatch(AppActionCallbackStatus.FAILURE);
112
- expect(response?.output?.message).toMatch('Test');
113
- expect(response.output.type).toMatch('system');
114
- });
115
-
116
- });
@@ -1,50 +0,0 @@
1
- import { AppActionCallBack, AppActionCallbackStatus } from "@contrail/app-framework";
2
-
3
- export class ErrorResponseObject {
4
-
5
- /** Returns a response, checking for multiple possible error details
6
- *
7
- * @param e
8
- * @returns
9
- */
10
- public static getResponse(e): AppActionCallBack {
11
- if(!e){
12
- const response: AppActionCallBack = {
13
- status: AppActionCallbackStatus.FAILURE,
14
- output: {
15
- message: 'No error provided.'
16
- }
17
- };
18
- return response;
19
- }
20
-
21
- const response: AppActionCallBack = {
22
- status: AppActionCallbackStatus.FAILURE,
23
- output: {
24
- message: e.message
25
- }
26
- };
27
- const output = response.output;
28
-
29
- //Errors when persisting in VibeIQ
30
- if(e.details) output.errorDetails = e.details;
31
-
32
- if(e.code) output.code = e.code;
33
- if(e.errno) output.errno = e.errno;
34
- if(e.type) output.type = e.type;
35
- if(e.name) output.errorName = e.name;
36
-
37
- //Has original cause
38
- if(e.cause){
39
- output.cause = {};
40
- const cause = output.cause;
41
- if(e.cause.code) cause.code = e.cause.code;
42
- if(e.cause.message) cause.message = e.cause.message;
43
- }
44
-
45
- if(e.stack){
46
- console.log('ErrorResponseObject.getResponse stack: ' + e.stack);
47
- }
48
- return response;
49
- }
50
- }
@@ -1,22 +0,0 @@
1
- export enum EventShortMessageStatus {
2
- SUCCESS = 'Success',
3
- FAILURE = 'Failure',
4
- CREATED = 'Created',
5
- ITEM_FAMILY_ID_MISSING = 'Item_family_id_missing',
6
- ITEM_FAMILY_NOT_FOUND = 'Item_family_not_found',
7
- PROJECT_ITEM_NOT_FOUND = 'Project_item_not_found',
8
- MISSING_IDENTIFIER_PROPERTIES = 'Missing_identifier_properties',
9
- MISSING_INPUT = 'Missing_input',
10
- NOT_CREATABLE = 'Not_creatable',
11
- NO_CHANGES = 'No_Changes',
12
- PRIMARY_CONTENT_UPDATED = 'Primary_Content_Updated',
13
- TOO_MANY_ENTITIES_FOUND = 'Too_Many_Entities_Found',
14
- UPDATED = 'Updated',
15
-
16
- //Publish
17
- NOT_PUBLISHABLE = 'Not_Publishable',
18
- NO_FEDERATION_INFO = 'No_Federation_Information',
19
- NO_EVENTS_TO_SEND = 'No_Events_to_Send',
20
- SENDING_EVENTS = 'Sending_Events',
21
-
22
- }
@@ -1,172 +0,0 @@
1
- import { Entities } from '@contrail/sdk';
2
-
3
- import { FederationRecord } from '../interfaces/interfaces';
4
- import pLimit from 'p-limit';
5
- const limit = pLimit(30);
6
-
7
- interface fedConfigDef {
8
- appIdentifier: string,
9
- federationSchema: string
10
- }
11
- const FED_CONFIG: fedConfigDef = {
12
- appIdentifier: '@vibeiq/flexplm-connector',
13
- federationSchema: 'DEFAULT'
14
- };
15
- export class Federation {
16
-
17
- private CHUNK_SIZE = 50;
18
-
19
- async getFederatedMappedRefId(entityType: string, entityId: string) {
20
- const criteria = {
21
- reference: entityType + ':' + entityId,
22
- appIdentifier: FED_CONFIG.appIdentifier,
23
- federationSchema: FED_CONFIG.federationSchema
24
- };
25
- console.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
26
- const fedRecords: FederationRecord[] = await new Entities().get({
27
- entityName: 'federation',
28
- criteria
29
- });
30
-
31
- const federatedId = (fedRecords[0])
32
- ? fedRecords[0]['mappedReference']
33
- : '';
34
-
35
- return federatedId;
36
- }
37
-
38
- async createFederatedRecord(eventBody) {
39
- const itemResults = eventBody.payload;
40
- for (let i = 0; i < itemResults.length; i++) {
41
- if (!itemResults[i].federatedId) {
42
- continue;
43
- }
44
- const payload: FederationRecord = {
45
- appIdentifier: FED_CONFIG.appIdentifier,
46
- reference: itemResults[i].entityReference,
47
- mappedReference: itemResults[i].federatedId,
48
- federationSchema: FED_CONFIG.federationSchema
49
- };
50
- // console.log('createFederatedRecord: ' + JSON.stringify(payload));
51
-
52
- try {
53
- const results = await new Entities().create({ entityName: 'federation', object: payload });
54
- return results;
55
- // console.log(JSON.stringify(results));
56
- } catch (error) {
57
- console.log('createFederatedRecord-error: ', error);
58
- throw new Error('Error creating federation record: ' + error.message);
59
- }
60
- }
61
- }
62
-
63
- async getFederationRecordFromMappedRefId(mappedRefId: string) {
64
- const criteria = {
65
- appIdentifier: FED_CONFIG.appIdentifier,
66
- mappedReference: mappedRefId,
67
- federationSchema: FED_CONFIG.federationSchema
68
- };
69
- try {
70
- const fedRecords: FederationRecord[] = await new Entities().get({
71
- entityName: 'federation',
72
- criteria
73
- });
74
- return (fedRecords && fedRecords[0]) ? fedRecords[0] : undefined;
75
- } catch (e) {
76
- console.log('getFederationData-error: ' + e.message);
77
- }
78
- return undefined;
79
- }
80
-
81
- static getEntityId(fedRecord: FederationRecord) {
82
- const entityString = fedRecord['reference'];
83
- const entitySplit = entityString.split(':');
84
- const entityType = entitySplit[0];
85
- const entityId = entitySplit[1];
86
-
87
- return { entityType, entityId };
88
-
89
- }
90
-
91
- async getEntityFromMappedRefId(mappedRefId: string) {
92
- // console.log('!---getEntityFromMappedRefId: ' + mappedRefId);
93
- const fedRecord = await this.getFederationRecordFromMappedRefId(mappedRefId);
94
- console.log('fedRecord: ' + JSON.stringify(fedRecord));
95
- if (!fedRecord) {
96
- //Not creating from FlexPLM at this time.
97
- console.log('Federation Record doesnt exist. Cant get entity!');
98
- return;
99
- }
100
-
101
- const { entityType, entityId } = Federation.getEntityId(fedRecord);
102
- // console.log(entityType + ':' + entityId);
103
- const criteria = {
104
- id: entityId
105
- };
106
- const entities = await new Entities().get({
107
- entityName: entityType,
108
- criteria
109
- });
110
- const entity = (entities && entities[0]) ? entities[0] : undefined;
111
- // console.log(' entities: ' +JSON.stringify(entities));
112
- return entity;
113
- }
114
-
115
- async getFederationRecordsFromIds(ids: string[]): Promise<FederationRecord[]> {
116
- const fedRecords = [];
117
- for (let i = 0; i < ids.length; i++) {
118
- const criteria = {
119
- reference: ids[i],
120
- appIdentifier: FED_CONFIG.appIdentifier,
121
- federationSchema: FED_CONFIG.federationSchema
122
- };
123
- // this.logger.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
124
- const recs: FederationRecord[] = await new Entities().get({
125
- entityName: 'federation',
126
- criteria
127
- });
128
- if (recs[0]) {
129
- fedRecords.push(recs[0]);
130
- }
131
- }
132
-
133
- return fedRecords;
134
- }
135
-
136
- async getFederationRecordsFromIdsBulk(ids: string[]): Promise<FederationRecord[]> {
137
-
138
- const chunks: string[][] = this.splitIntoChunksByLen(ids, this.CHUNK_SIZE);
139
- const fedRecords = [];
140
- const federatedPromises = [];
141
- const entities: Entities = new Entities();
142
- for (const chunk of chunks) {
143
- const fedPromise = limit(async () => {
144
- const criteria = {
145
- references: chunk,
146
- appIdentifier: FED_CONFIG.appIdentifier,
147
- federationSchema: FED_CONFIG.federationSchema
148
- };
149
- // this.logger.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
150
- const records: FederationRecord[] = await entities.get({
151
- entityName: 'federation',
152
- criteria
153
- });
154
- fedRecords.push(...records);
155
-
156
- });
157
- federatedPromises.push(fedPromise);
158
- }
159
- await Promise.all(federatedPromises);
160
-
161
- return fedRecords;
162
- }
163
-
164
- splitIntoChunksByLen(arr, len) {
165
- const chunks = [], n = arr?.length;
166
- let i = 0;
167
- while (i < n) {
168
- chunks.push(arr.slice(i, i += len));
169
- }
170
- return chunks;
171
- }
172
- }
@@ -1,132 +0,0 @@
1
-
2
- import { FlexPLMConnect } from './flexplm-connect';
3
- import { FCConfig } from '../interfaces/interfaces';
4
-
5
- const mockJsonData = { items: [{ id: '123', name: 'test' }] };
6
-
7
- const mockResponse = (status: number, json = mockJsonData) => ({
8
- status,
9
- json: jest.fn().mockResolvedValue(json),
10
- text: jest.fn().mockResolvedValue('error text'),
11
- });
12
-
13
- const globalFetch = global.fetch;
14
-
15
- beforeEach(() => {
16
- global.fetch = jest.fn().mockResolvedValue(mockResponse(200));
17
- });
18
-
19
- afterAll(() => {
20
- global.fetch = globalFetch;
21
- });
22
-
23
- const createConfig = (overrides?: Partial<FCConfig>): FCConfig => ({
24
- apiHost: 'https://flexplm.example.com',
25
- urlContext: '/FlexPLM',
26
- vibeEventEndpoint: '/api/events',
27
- csrfEndpoint: '/csrf',
28
- plmEnviornment: 'test',
29
- userName: () => 'user',
30
- password: () => 'pass',
31
- itemPreDevelopmentLifecycleStages: [],
32
- payloadDefaultAsArray: true,
33
- ...overrides,
34
- });
35
-
36
- describe('FlexPLMConnect.getRequest', () => {
37
-
38
- it('should call default URL with urlContext when no params provided', async () => {
39
- const connect = new FlexPLMConnect(createConfig());
40
- await connect.getRequest();
41
-
42
- expect(global.fetch).toHaveBeenCalledWith(
43
- 'https://flexplm.example.com/FlexPLM/servlet/rest/api/events',
44
- expect.objectContaining({ method: 'GET' }),
45
- );
46
- });
47
-
48
- it('should use the constructor endpoint in the default URL', async () => {
49
- const connect = new FlexPLMConnect(createConfig(), '/custom/endpoint');
50
- await connect.getRequest();
51
-
52
- expect(global.fetch).toHaveBeenCalledWith(
53
- 'https://flexplm.example.com/FlexPLM/servlet/rest/custom/endpoint',
54
- expect.any(Object),
55
- );
56
- });
57
-
58
- it('should return parsed JSON by default', async () => {
59
- const connect = new FlexPLMConnect(createConfig());
60
- const result = await connect.getRequest();
61
- expect(result).toEqual(mockJsonData);
62
- });
63
-
64
- it('should use urlPath when provided', async () => {
65
- const connect = new FlexPLMConnect(createConfig());
66
- await connect.getRequest({ urlPath: '/custom/path' });
67
-
68
- expect(global.fetch).toHaveBeenCalledWith(
69
- 'https://flexplm.example.com/FlexPLM/custom/path',
70
- expect.any(Object),
71
- );
72
- });
73
-
74
- it('should exclude urlContext when includeUrlContext is false', async () => {
75
- const connect = new FlexPLMConnect(createConfig());
76
- await connect.getRequest({ includeUrlContext: false });
77
-
78
- expect(global.fetch).toHaveBeenCalledWith(
79
- 'https://flexplm.example.com/servlet/rest/api/events',
80
- expect.any(Object),
81
- );
82
- });
83
-
84
- it('should exclude urlContext with custom urlPath', async () => {
85
- const connect = new FlexPLMConnect(createConfig());
86
- await connect.getRequest({ urlPath: '/custom/path', includeUrlContext: false });
87
-
88
- expect(global.fetch).toHaveBeenCalledWith(
89
- 'https://flexplm.example.com/custom/path',
90
- expect.any(Object),
91
- );
92
- });
93
-
94
- it('should return full response when returnFullResponse is true', async () => {
95
- const rawResponse = mockResponse(200);
96
- (global.fetch as jest.Mock).mockResolvedValue(rawResponse);
97
-
98
- const connect = new FlexPLMConnect(createConfig());
99
- const result = await connect.getRequest({ returnFullResponse: true });
100
-
101
- expect(result).toBe(rawResponse);
102
- expect(rawResponse.json).not.toHaveBeenCalled();
103
- });
104
-
105
- it('should throw on status >= 300', async () => {
106
- (global.fetch as jest.Mock).mockResolvedValue(mockResponse(404));
107
-
108
- const connect = new FlexPLMConnect(createConfig());
109
- await expect(connect.getRequest()).rejects.toThrow('Error connecting to FlexPLM:status: 404');
110
- });
111
-
112
- it('should throw on status >= 300 even with returnFullResponse', async () => {
113
- (global.fetch as jest.Mock).mockResolvedValue(mockResponse(500));
114
-
115
- const connect = new FlexPLMConnect(createConfig());
116
- await expect(connect.getRequest({ returnFullResponse: true })).rejects.toThrow(
117
- 'Error connecting to FlexPLM:status: 500',
118
- );
119
- });
120
-
121
- it('should throw when response.json() fails', async () => {
122
- const badResponse = {
123
- status: 200,
124
- json: jest.fn().mockRejectedValue(new Error('Invalid JSON')),
125
- text: jest.fn().mockResolvedValue('not json'),
126
- };
127
- (global.fetch as jest.Mock).mockResolvedValue(badResponse);
128
-
129
- const connect = new FlexPLMConnect(createConfig());
130
- await expect(connect.getRequest()).rejects.toThrow('Error getting json data from FlexPLM: Invalid JSON');
131
- });
132
- });
@@ -1,208 +0,0 @@
1
- import { Logger } from '@contrail/app-framework';
2
- import { FCConfig, FlexPLMResponseData, PayloadType } from '../interfaces/interfaces';
3
-
4
- export class FlexPLMConnect {
5
- private config: FCConfig;
6
- private vibeEventEndpoint = '';
7
- private staticHeaders = undefined;
8
- public payloadSendAsArray = true;
9
- constructor(_config: FCConfig, endPoint = undefined, payloadAsArray = undefined) {
10
- this.config = _config;
11
- this.vibeEventEndpoint = (endPoint)
12
- ? endPoint
13
- : this.config.vibeEventEndpoint;
14
- this.payloadSendAsArray = (payloadAsArray != undefined)
15
- ? payloadAsArray
16
- : this.config['payloadDefaultAsArray'];
17
- if(this.config?.flexplmConnect?.staticHeaders){
18
- this.staticHeaders = this.config?.flexplmConnect?.staticHeaders;
19
- }
20
- }
21
-
22
- /////////////////////////////////////////////////////////////////////////////
23
- ///////// Custom getRequestOptions: start
24
- /////////////////////////////////////////////////////////////////////////////
25
- private getRequestOptions(method: string) {
26
- const csrfOptions = {
27
- method,
28
- headers: {
29
- 'Content-Type': 'application/json',
30
- PLM_ENV: this.config.plmEnviornment,
31
- Authorization: 'Basic ' + Buffer.from(`${this.config.userName()}:${this.config.password()}`, 'binary').toString('base64')
32
- }
33
- };
34
- if(this.staticHeaders){
35
- Object.assign(csrfOptions.headers, this.staticHeaders);
36
- }
37
- if(Logger.isInfoOn()){
38
- const logOptions = JSON.parse(JSON.stringify(csrfOptions));
39
- logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
40
- console.info('csrfOptions: ' + JSON.stringify(logOptions));
41
- }
42
- return csrfOptions;
43
- }
44
- /////////////////////////////////////////////////////////////////////////////
45
- ///////// Custom getRequestOptions: end
46
- /////////////////////////////////////////////////////////////////////////////
47
-
48
- async getCSRF() {
49
- const urlContext = this.config.urlContext;
50
- const csrfEndpoint = this.config.csrfEndpoint;
51
- const csrfURL: string = this.config.apiHost + urlContext + csrfEndpoint;
52
- console.info('csrfURL: ' + csrfURL);
53
-
54
- const csrfOptions = this.getRequestOptions('GET');
55
-
56
- const response = await fetch(csrfURL, csrfOptions);
57
- if(response.status >= 300){
58
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
59
- console.error(message);
60
- console.error(await response.text());
61
- const e = new Error(message);
62
- e['httpResponseStatus'] = response.status;
63
- throw e;
64
- }
65
-
66
- try{
67
-
68
- const body = await response.json();
69
-
70
- const nonce_key = body.items[0].attributes.nonce_key;
71
- const nonce = body.items[0].attributes.nonce;
72
- console.info('nonce_key: ' + nonce_key);
73
- console.info('nonce: ' + nonce);
74
- return {
75
- nonce_key,
76
- nonce
77
- };
78
- }catch(e){
79
- const message = 'Error connecting to FlexPLM: ' + e.message;
80
- console.error(message);
81
- console.error(await response.text());
82
- throw new Error(message);
83
- }
84
- }
85
-
86
- async sendRequest(csrf, payload) {
87
-
88
- if(this.payloadSendAsArray && !Array.isArray(payload)){
89
- payload = [payload];
90
- }
91
-
92
- const xferOptions = this.getRequestOptions('POST');
93
-
94
- xferOptions['body'] = JSON.stringify(payload);
95
- xferOptions.headers[csrf.nonce_key] = csrf.nonce;
96
-
97
- const urlContext = this.config.urlContext;
98
- const vibeEventsURL: string = this.config.apiHost + urlContext + '/servlet/rest' + this.vibeEventEndpoint;
99
-
100
- if(Logger.isInfoOn()){
101
- console.info('Request:');
102
- console.info('vibeEventsURL: ' + vibeEventsURL);
103
- const logOptions = JSON.parse(JSON.stringify(xferOptions));
104
- logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
105
- console.info('csrfOptions: ' + JSON.stringify(logOptions));
106
- console.info('Making call to xfer data to FlexPLM');
107
- }
108
- const eventResponse = await fetch(vibeEventsURL, xferOptions);
109
- return eventResponse;
110
- }
111
-
112
- protected async processRequest(payload:any){
113
- if(!payload){
114
- const message = 'No payload to send to FlexPLM';
115
- console.error(message);
116
- throw new Error(message);
117
- }
118
- if(Logger.isInfoOn()){
119
- console.info('payload: ' + JSON.stringify(payload));
120
- }
121
-
122
- const csrf = await this.getCSRF();
123
- if(!csrf){
124
- const message = 'Failed to get CSRF nonce';
125
- console.error(message);
126
- throw new Error(message);
127
- }
128
-
129
- const response = await this.sendRequest(csrf, payload);
130
- const status = response.status;
131
- if(status >= 300){
132
- const message = 'Error sending data to FlexPLM:status: ' + response.status;
133
- console.error(message);
134
- console.error(await response.text());
135
- const e = new Error(message);
136
- e['httpResponseStatus'] = status;
137
- throw e;
138
- }
139
-
140
- try{
141
- const res: FlexPLMResponseData = {
142
- status,
143
- };
144
- if(![204, 205].includes(status)){
145
- try{
146
- const data = await response.json();
147
- res.data = data;
148
- } catch(e){
149
- console.error('Error getting response body. Setting {} body: ' + e);
150
- res.data = {};
151
- }
152
- }
153
-
154
- console.log('eventResponse.status: ' + status);
155
- // console.log('eventBody: ', JSON.stringify(data));
156
- return res;
157
-
158
- }catch(e){
159
- const message = 'Error getting json data from FlexPLM: ' + e.message;
160
- console.error(message);
161
- console.error(await response.text());
162
- throw new Error(message);
163
- }
164
-
165
- }
166
- async sendToFlexPLM( payload: PayloadType){
167
- return await this.processRequest(payload);
168
- }
169
-
170
- async sendMultipleToFlexPLM(payload: PayloadType[]){
171
- return await this.processRequest(payload);
172
- }
173
-
174
- /** Runs a GET request to FlexPLM.
175
- * @param params - Optional configuration for the request.
176
- * @param params.urlPath - Custom URL path to use instead of the default `/servlet/rest` + endpoint.
177
- * @param params.includeUrlContext - Whether to include the urlContext in the URL. Defaults to `true`.
178
- * @param params.returnFullResponse - If `true`, returns the raw `Response` object instead of parsed JSON. Defaults to `false`.
179
- * @returns The parsed JSON response body, or the raw `Response` object if `returnFullResponse` is `true`.
180
- */
181
- async getRequest(params?: { urlPath?: string; includeUrlContext?: boolean; returnFullResponse?: boolean }): Promise<Response | unknown>{
182
- const { urlPath, includeUrlContext = true, returnFullResponse = false } = params || {};
183
- const urlContext = includeUrlContext ? this.config.urlContext : '';
184
- const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
185
- const vibeEventsURL: string = this.config.apiHost + urlContext + path;
186
- const csrfOptions = this.getRequestOptions('GET');
187
- const response = await fetch(vibeEventsURL, csrfOptions);
188
-
189
- if(response.status >= 300){
190
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
191
- console.error(message);
192
- console.error(await response.text());
193
- throw new Error(message);
194
- }
195
- if(returnFullResponse){
196
- return response;
197
- }
198
- try {
199
- const data = await response.json();
200
- return data;
201
- } catch(e){
202
- const message = 'Error getting json data from FlexPLM: ' + e.message;
203
- console.error(message);
204
- console.error(await response.text());
205
- throw new Error(message);
206
- }
207
- }
208
- }