@contrail/flexplm 1.8.1 → 1.8.2

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.
@@ -5,6 +5,10 @@ export declare class FlexPLMConnect {
5
5
  private staticHeaders;
6
6
  payloadSendAsArray: boolean;
7
7
  constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
8
+ /** When true, a success response whose body is not JSON is returned as `data: { responseBody }`
9
+ * instead of failing the event. Configured via `flexplmConnect.allowNonJsonResponse` (default false).
10
+ */
11
+ private get allowNonJsonResponse();
8
12
  private get sessionOptions();
9
13
  /**
10
14
  * Waits until no cold session acquisition is running for this key.
@@ -28,6 +32,11 @@ export declare class FlexPLMConnect {
28
32
  private fetchCSRF;
29
33
  sendRequest(csrf: any, payload: any): Promise<Response>;
30
34
  protected processRequest(payload: any): Promise<FlexPLMResponseData>;
35
+ /** Builds the error thrown for a failed FlexPLM response. The response body is put on
36
+ * `details` so that it is surfaced as `errorDetails` in the event output.
37
+ * The body is parsed as JSON when possible, otherwise it is kept as the raw text.
38
+ */
39
+ private createResponseError;
31
40
  sendToFlexPLM(payload: PayloadType): Promise<FlexPLMResponseData>;
32
41
  sendMultipleToFlexPLM(payload: PayloadType[]): Promise<FlexPLMResponseData>;
33
42
  /** Runs a GET request to FlexPLM.
@@ -68,6 +68,13 @@ class FlexPLMConnect {
68
68
  this.staticHeaders = this.config?.flexplmConnect?.staticHeaders;
69
69
  }
70
70
  }
71
+ /** When true, a success response whose body is not JSON is returned as `data: { responseBody }`
72
+ * instead of failing the event. Configured via `flexplmConnect.allowNonJsonResponse` (default false).
73
+ */
74
+ get allowNonJsonResponse() {
75
+ const allow = this.config?.flexplmConnect?.allowNonJsonResponse;
76
+ return allow === true || String(allow).toLowerCase() === 'true';
77
+ }
71
78
  /////////////////////////////////////////////////////////////////////////////
72
79
  ///////// ET-390 - Session reuse: start
73
80
  /////////////////////////////////////////////////////////////////////////////
@@ -351,37 +358,65 @@ class FlexPLMConnect {
351
358
  // Added for Session reuse - ET-390 - Ends
352
359
  const status = response.status;
353
360
  if (status >= 300) {
354
- const message = 'Error sending data to FlexPLM:status: ' + response.status;
355
- console.error(message);
356
- console.error(await response.text());
357
- const e = new Error(message);
358
- e['httpResponseStatus'] = status;
359
- throw e;
361
+ let responseBody;
362
+ try {
363
+ responseBody = await response.text();
364
+ }
365
+ catch (e) {
366
+ console.error('Error reading FlexPLM error response body: ' + e?.message);
367
+ }
368
+ throw this.createResponseError('Error sending data to FlexPLM:status: ' + status, status, responseBody);
360
369
  }
361
- try {
362
- const res = {
363
- status,
364
- };
365
- if (![204, 205].includes(status)) {
366
- try {
367
- const data = await response.json();
368
- res.data = data;
369
- }
370
- catch (e) {
371
- console.error('Error getting response body. Setting {} body: ' + e);
370
+ const res = {
371
+ status,
372
+ };
373
+ if (![204, 205].includes(status)) {
374
+ let responseBody;
375
+ try {
376
+ responseBody = await response.text();
377
+ if (responseBody.trim() === '') {
378
+ // An empty body is a valid success response.
372
379
  res.data = {};
373
380
  }
381
+ else {
382
+ try {
383
+ res.data = JSON.parse(responseBody);
384
+ }
385
+ catch (parseError) {
386
+ if (!this.allowNonJsonResponse)
387
+ throw parseError;
388
+ console.warn('FlexPLM response is not JSON; allowNonJsonResponse is enabled, returning raw body. status: ' + status);
389
+ res.data = { responseBody };
390
+ }
391
+ }
392
+ }
393
+ catch (e) {
394
+ throw this.createResponseError('Error getting json data from FlexPLM:status: ' + status + ': ' + e?.message, status, responseBody);
374
395
  }
375
- console.log('eventResponse.status: ' + status);
376
- // console.log('eventBody: ', JSON.stringify(data));
377
- return res;
378
396
  }
379
- catch (e) {
380
- const message = 'Error getting json data from FlexPLM: ' + e.message;
381
- console.error(message);
382
- console.error(await response.text());
383
- throw new Error(message);
397
+ console.log('eventResponse.status: ' + status);
398
+ return res;
399
+ }
400
+ /** Builds the error thrown for a failed FlexPLM response. The response body is put on
401
+ * `details` so that it is surfaced as `errorDetails` in the event output.
402
+ * The body is parsed as JSON when possible, otherwise it is kept as the raw text.
403
+ */
404
+ createResponseError(message, status, responseBody) {
405
+ console.error(message);
406
+ console.error('responseBody: ' + responseBody);
407
+ let body = responseBody;
408
+ if (responseBody) {
409
+ try {
410
+ body = JSON.parse(responseBody);
411
+ }
412
+ catch {
413
+ // keep raw text
414
+ }
384
415
  }
416
+ const e = new Error(message);
417
+ e['httpResponseStatus'] = status;
418
+ e['details'] = { httpResponseStatus: status, responseBody: body };
419
+ return e;
385
420
  }
386
421
  async sendToFlexPLM(payload) {
387
422
  return await this.processRequest(payload);
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
3
26
  const flexplm_connect_1 = require("./flexplm-connect");
4
27
  const app_framework_1 = require("@contrail/app-framework");
@@ -6,7 +29,7 @@ const mockJsonData = { items: [{ id: '123', name: 'test' }] };
6
29
  const mockResponse = (status, json = mockJsonData) => ({
7
30
  status,
8
31
  json: jest.fn().mockResolvedValue(json),
9
- text: jest.fn().mockResolvedValue('error text'),
32
+ text: jest.fn().mockResolvedValue(JSON.stringify(json)),
10
33
  });
11
34
  const globalFetch = global.fetch;
12
35
  beforeEach(() => {
@@ -34,7 +57,7 @@ const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'n1'
34
57
  const resp = (status, setCookie = [], json = csrfBody) => ({
35
58
  status,
36
59
  json: jest.fn().mockResolvedValue(json),
37
- text: jest.fn().mockResolvedValue('error text'),
60
+ text: jest.fn().mockResolvedValue(JSON.stringify(json)),
38
61
  headers: { getSetCookie: () => setCookie, get: () => null },
39
62
  });
40
63
  let userCounter = 0;
@@ -138,6 +161,137 @@ describe('FlexPLMConnect.sendRequest', () => {
138
161
  consoleInfoSpy.mockRestore();
139
162
  });
140
163
  });
164
+ describe('FlexPLMConnect.sendToFlexPLM response body handling', () => {
165
+ const payload = { id: '123' };
166
+ const postResp = (status, text) => ({
167
+ status,
168
+ json: jest.fn(),
169
+ text,
170
+ headers: { getSetCookie: () => [], get: () => null },
171
+ });
172
+ let consoleErrorSpy;
173
+ beforeEach(() => {
174
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
175
+ });
176
+ afterEach(() => {
177
+ consoleErrorSpy.mockRestore();
178
+ });
179
+ it('should return the parsed JSON body on success', async () => {
180
+ fetchMock()
181
+ .mockResolvedValueOnce(resp(200))
182
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue('{"ok":true}')));
183
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
184
+ expect(result).toEqual({ status: 200, data: { ok: true } });
185
+ });
186
+ it('should fail when the response body is not valid JSON', async () => {
187
+ fetchMock()
188
+ .mockResolvedValueOnce(resp(200))
189
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue('<html>Server Error</html>')));
190
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
191
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200');
192
+ await expect(promise).rejects.toHaveProperty('httpResponseStatus', 200);
193
+ await expect(promise).rejects.toHaveProperty('details', {
194
+ httpResponseStatus: 200,
195
+ responseBody: '<html>Server Error</html>',
196
+ });
197
+ expect(consoleErrorSpy).toHaveBeenCalledWith('responseBody: <html>Server Error</html>');
198
+ });
199
+ it.each(['', ' \n'])('should succeed with empty data when the response body is empty (%j)', async (body) => {
200
+ fetchMock()
201
+ .mockResolvedValueOnce(resp(200))
202
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue(body)));
203
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
204
+ expect(result).toEqual({ status: 200, data: {} });
205
+ });
206
+ it('should fail when reading the response body throws', async () => {
207
+ fetchMock()
208
+ .mockResolvedValueOnce(resp(200))
209
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockRejectedValue(new Error('stream aborted'))));
210
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
211
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200: stream aborted');
212
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 200, responseBody: undefined });
213
+ });
214
+ it('should include a JSON error body, parsed, on the error for status >= 300', async () => {
215
+ const errorBody = { message: 'Attribute xyz is not valid', code: 'INVALID_ATTR' };
216
+ fetchMock()
217
+ .mockResolvedValueOnce(resp(200))
218
+ .mockResolvedValueOnce(postResp(400, jest.fn().mockResolvedValue(JSON.stringify(errorBody))));
219
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
220
+ await expect(promise).rejects.toThrow('Error sending data to FlexPLM:status: 400');
221
+ await expect(promise).rejects.toHaveProperty('httpResponseStatus', 400);
222
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 400, responseBody: errorBody });
223
+ });
224
+ it('should include a non-JSON error body, as text, on the error for status >= 300', async () => {
225
+ fetchMock()
226
+ .mockResolvedValueOnce(resp(200))
227
+ .mockResolvedValueOnce(postResp(500, jest.fn().mockResolvedValue('Internal Server Error')));
228
+ await expect(new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload))
229
+ .rejects.toHaveProperty('details', { httpResponseStatus: 500, responseBody: 'Internal Server Error' });
230
+ });
231
+ it('should still fail with the status error when reading the error body throws', async () => {
232
+ fetchMock()
233
+ .mockResolvedValueOnce(resp(200))
234
+ .mockResolvedValueOnce(postResp(502, jest.fn().mockRejectedValue(new Error('stream aborted'))));
235
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
236
+ await expect(promise).rejects.toThrow('Error sending data to FlexPLM:status: 502');
237
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 502, responseBody: undefined });
238
+ });
239
+ it('should surface the error body as errorDetails in the event output', async () => {
240
+ const { ErrorResponseObject } = await Promise.resolve().then(() => __importStar(require('./error-response-object')));
241
+ fetchMock()
242
+ .mockResolvedValueOnce(resp(200))
243
+ .mockResolvedValueOnce(postResp(400, jest.fn().mockResolvedValue('{"message":"bad"}')));
244
+ const error = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload).catch(e => e);
245
+ expect(ErrorResponseObject.getResponse(error).output.errorDetails)
246
+ .toEqual({ httpResponseStatus: 400, responseBody: { message: 'bad' } });
247
+ });
248
+ describe('flexplmConnect.allowNonJsonResponse', () => {
249
+ const connectWith = (allowNonJsonResponse) => new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser, flexplmConnect: { allowNonJsonResponse } }));
250
+ const postReturns = (status, body) => fetchMock()
251
+ .mockResolvedValueOnce(resp(200))
252
+ .mockResolvedValueOnce(postResp(status, jest.fn().mockResolvedValue(body)));
253
+ it.each([true, 'true', 'TRUE'])('should return a non-JSON body as data.responseBody when set to %j', async (flag) => {
254
+ const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
255
+ postReturns(200, 'OK - event accepted');
256
+ const result = await connectWith(flag).sendToFlexPLM(payload);
257
+ expect(result).toEqual({ status: 200, data: { responseBody: 'OK - event accepted' } });
258
+ expect(consoleWarnSpy).toHaveBeenCalled();
259
+ consoleWarnSpy.mockRestore();
260
+ });
261
+ it.each([false, 'false', undefined, 1])('should still fail on a non-JSON body when set to %j', async (flag) => {
262
+ postReturns(200, 'OK - event accepted');
263
+ await expect(connectWith(flag).sendToFlexPLM(payload))
264
+ .rejects.toThrow('Error getting json data from FlexPLM:status: 200');
265
+ });
266
+ it('should still parse a JSON body when enabled', async () => {
267
+ postReturns(200, '{"ok":true}');
268
+ const result = await connectWith(true).sendToFlexPLM(payload);
269
+ expect(result).toEqual({ status: 200, data: { ok: true } });
270
+ });
271
+ it('should still fail when reading the body throws, even when enabled', async () => {
272
+ fetchMock()
273
+ .mockResolvedValueOnce(resp(200))
274
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockRejectedValue(new Error('stream aborted'))));
275
+ const promise = connectWith(true).sendToFlexPLM(payload);
276
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200: stream aborted');
277
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 200, responseBody: undefined });
278
+ });
279
+ it('should still fail on status >= 300 with a non-JSON body, even when enabled', async () => {
280
+ postReturns(500, 'Internal Server Error');
281
+ await expect(connectWith(true).sendToFlexPLM(payload))
282
+ .rejects.toThrow('Error sending data to FlexPLM:status: 500');
283
+ });
284
+ });
285
+ it.each([204, 205])('should not read the body for status %s', async (status) => {
286
+ const text = jest.fn();
287
+ fetchMock()
288
+ .mockResolvedValueOnce(resp(200))
289
+ .mockResolvedValueOnce(postResp(status, text));
290
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
291
+ expect(result).toEqual({ status });
292
+ expect(text).not.toHaveBeenCalled();
293
+ });
294
+ });
141
295
  // Added for Session reuse - ET-390 - Starts
142
296
  describe('FlexPLMConnect session reuse', () => {
143
297
  const payload = { id: '123' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/flexplm",
3
- "version": "1.8.1",
3
+ "version": "1.8.2",
4
4
  "description": "Library used for integration with flexplm.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",