@contrail/flexplm 1.3.2-alpha.328325d → 1.3.2-alpha.3ffe557

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 (111) hide show
  1. package/lib/cli/commands/compile.d.ts +4 -0
  2. package/lib/cli/commands/compile.js +73 -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 +5 -0
  6. package/lib/cli/commands/create.js +77 -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 +17 -0
  10. package/lib/cli/commands/upload.js +228 -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 +5 -0
  14. package/lib/cli/index.js +70 -0
  15. package/lib/cli/index.spec.d.ts +1 -0
  16. package/lib/cli/index.spec.js +85 -0
  17. package/lib/cli/template/mapping-template.ts.template +62 -0
  18. package/lib/entity-processor/base-entity-processor.d.ts +47 -5
  19. package/lib/entity-processor/base-entity-processor.js +53 -28
  20. package/lib/entity-processor/base-entity-processor.spec.js +1 -103
  21. package/lib/index.d.ts +1 -0
  22. package/lib/index.js +1 -0
  23. package/lib/interfaces/mapping-file.d.ts +460 -0
  24. package/lib/interfaces/mapping-file.js +2 -0
  25. package/lib/publish/base-process-publish-assortment.d.ts +25 -0
  26. package/lib/publish/base-process-publish-assortment.js +60 -6
  27. package/lib/publish/base-process-publish-assortment.spec.js +22 -4
  28. package/lib/publish/mockData.js +5 -0
  29. package/lib/transform/identifier-conversion-spec-mockData.js +34 -6
  30. package/lib/transform/identifier-conversion.d.ts +36 -0
  31. package/lib/transform/identifier-conversion.js +36 -0
  32. package/lib/transform/identifier-conversion.spec.js +4 -0
  33. package/lib/util/config-defaults.js +3 -0
  34. package/lib/util/config-defaults.spec.js +9 -0
  35. package/lib/util/data-converter-spec-mockData.js +17 -3
  36. package/lib/util/data-converter.d.ts +97 -0
  37. package/lib/util/data-converter.js +133 -1
  38. package/lib/util/data-converter.spec.js +68 -0
  39. package/lib/util/error-response-object.d.ts +5 -0
  40. package/lib/util/error-response-object.js +7 -0
  41. package/lib/util/event-short-message-status.js +1 -0
  42. package/lib/util/federation.js +8 -0
  43. package/lib/util/flexplm-connect.d.ts +7 -0
  44. package/lib/util/flexplm-connect.js +14 -0
  45. package/lib/util/logger-config.js +1 -0
  46. package/lib/util/map-util-spec-mockData.js +17 -3
  47. package/lib/util/map-utils.d.ts +27 -0
  48. package/lib/util/map-utils.js +27 -0
  49. package/lib/util/thumbnail-util.d.ts +21 -0
  50. package/lib/util/thumbnail-util.js +28 -1
  51. package/lib/util/thumbnail-util.spec.js +6 -0
  52. package/lib/util/type-conversion-utils-spec-mockData.js +3 -3
  53. package/lib/util/type-conversion-utils.d.ts +140 -0
  54. package/lib/util/type-conversion-utils.js +143 -0
  55. package/lib/util/type-defaults.d.ts +58 -0
  56. package/lib/util/type-defaults.js +58 -0
  57. package/lib/util/type-defaults.spec.js +5 -5
  58. package/lib/util/type-utils.d.ts +21 -0
  59. package/lib/util/type-utils.js +23 -0
  60. package/lib/util/type-utils.spec.js +2 -0
  61. package/package.json +21 -6
  62. package/scripts/copy-template.js +10 -0
  63. package/.github/pull_request_template.md +0 -31
  64. package/.github/workflows/flexplm-lib.yml +0 -27
  65. package/.github/workflows/publish-to-npm.yml +0 -121
  66. package/CHANGELOG.md +0 -35
  67. package/publish.bat +0 -5
  68. package/publish.sh +0 -5
  69. package/src/entity-processor/base-entity-processor.spec.ts +0 -582
  70. package/src/entity-processor/base-entity-processor.ts +0 -565
  71. package/src/flexplm-request.ts +0 -28
  72. package/src/flexplm-utils.spec.ts +0 -27
  73. package/src/flexplm-utils.ts +0 -29
  74. package/src/index.ts +0 -22
  75. package/src/interfaces/interfaces.ts +0 -122
  76. package/src/interfaces/item-family-changes.ts +0 -67
  77. package/src/interfaces/publish-change-data.ts +0 -43
  78. package/src/publish/base-process-publish-assortment-callback.ts +0 -50
  79. package/src/publish/base-process-publish-assortment.spec.ts +0 -1992
  80. package/src/publish/base-process-publish-assortment.ts +0 -1134
  81. package/src/publish/mockData.ts +0 -4561
  82. package/src/transform/identifier-conversion-spec-mockData.ts +0 -496
  83. package/src/transform/identifier-conversion.spec.ts +0 -354
  84. package/src/transform/identifier-conversion.ts +0 -282
  85. package/src/util/config-defaults.spec.ts +0 -350
  86. package/src/util/config-defaults.ts +0 -93
  87. package/src/util/data-converter-spec-mockData.ts +0 -231
  88. package/src/util/data-converter.spec.ts +0 -1041
  89. package/src/util/data-converter.ts +0 -762
  90. package/src/util/error-response-object.spec.ts +0 -116
  91. package/src/util/error-response-object.ts +0 -50
  92. package/src/util/event-short-message-status.ts +0 -22
  93. package/src/util/federation.ts +0 -172
  94. package/src/util/flexplm-connect.spec.ts +0 -132
  95. package/src/util/flexplm-connect.ts +0 -208
  96. package/src/util/logger-config.ts +0 -20
  97. package/src/util/map-util-spec-mockData.ts +0 -231
  98. package/src/util/map-utils.spec.ts +0 -103
  99. package/src/util/map-utils.ts +0 -41
  100. package/src/util/mockData.ts +0 -101
  101. package/src/util/thumbnail-util.spec.ts +0 -508
  102. package/src/util/thumbnail-util.ts +0 -272
  103. package/src/util/type-conversion-utils-spec-mockData.ts +0 -271
  104. package/src/util/type-conversion-utils.spec.ts +0 -968
  105. package/src/util/type-conversion-utils.ts +0 -460
  106. package/src/util/type-defaults.spec.ts +0 -669
  107. package/src/util/type-defaults.ts +0 -281
  108. package/src/util/type-utils.spec.ts +0 -227
  109. package/src/util/type-utils.ts +0 -144
  110. package/tsconfig.json +0 -24
  111. 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
- }