@sgedda/mockifyer-fetch 1.8.7 → 1.8.10

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.
@@ -6,6 +6,7 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
6
6
  private proxyBaseUrl?;
7
7
  private proxyScenario?;
8
8
  private proxyRecordOnMiss;
9
+ private clientId?;
9
10
  constructor(config?: {
10
11
  baseUrl?: string;
11
12
  defaultHeaders?: Record<string, string>;
@@ -14,6 +15,7 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
14
15
  scenario?: string;
15
16
  recordOnMiss?: boolean;
16
17
  };
18
+ clientId?: string;
17
19
  });
18
20
  protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
19
21
  protected getDefaultHeaders(): Record<string, string>;
@@ -10,6 +10,7 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
10
10
  this.proxyBaseUrl = config?.proxy?.baseUrl;
11
11
  this.proxyScenario = config?.proxy?.scenario;
12
12
  this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
13
+ this.clientId = config?.clientId;
13
14
  }
14
15
  async performRequest(config) {
15
16
  // Check if this is a mock response (set by Mockifyer interceptor)
@@ -56,10 +57,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
56
57
  const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
57
58
  const proxyResponse = await fetchFn(proxyUrl, {
58
59
  method: 'POST',
59
- headers: { 'content-type': 'application/json' },
60
+ headers: {
61
+ 'content-type': 'application/json',
62
+ ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
63
+ },
60
64
  body: JSON.stringify({
61
65
  url,
62
66
  method: requestConfig.method,
67
+ clientId: this.clientId,
63
68
  headers: (() => {
64
69
  const out = {};
65
70
  headers.forEach((value, key) => {
package/dist/index.js CHANGED
@@ -82,6 +82,8 @@ class MockifyerClass {
82
82
  }
83
83
  // Store config BEFORE any modifications
84
84
  this.config = { ...config }; // Create a copy to avoid mutations
85
+ // Resolve client lane id (env/config/fallback); used for Redis per-client scenario overrides and proxy headers.
86
+ this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
85
87
  // Initialize test generator if test generation is enabled
86
88
  if (config.generateTests?.enabled) {
87
89
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -93,6 +95,7 @@ class MockifyerClass {
93
95
  options: {
94
96
  ...config.databaseProvider.options,
95
97
  mockDataPath: config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
98
+ clientId: this.config.clientId,
96
99
  },
97
100
  };
98
101
  this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, providerConfig);
@@ -112,7 +115,8 @@ class MockifyerClass {
112
115
  this.httpClient = new fetch_client_1.FetchHTTPClient({
113
116
  baseUrl: config.baseUrl,
114
117
  defaultHeaders: config.defaultHeaders,
115
- proxy: config.proxy
118
+ proxy: config.proxy,
119
+ clientId: this.config.clientId,
116
120
  });
117
121
  if (!config.recordSameEndpoints) {
118
122
  this.loadMockData();
@@ -200,7 +204,7 @@ class MockifyerClass {
200
204
  console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
201
205
  return undefined;
202
206
  }
203
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath);
207
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath, this.config.clientId);
204
208
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
205
209
  if (!fs.existsSync(scenarioPath)) {
206
210
  mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
@@ -221,8 +225,11 @@ class MockifyerClass {
221
225
  }
222
226
  const mockKey = this.generateRequestKey(mockData.request);
223
227
  if (mockKey === requestKey) {
224
- exactMatch = { mockData, filename: file, filePath };
225
- break;
228
+ if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
229
+ exactMatch = { mockData, filename: file, filePath };
230
+ break;
231
+ }
232
+ continue;
226
233
  }
227
234
  if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
228
235
  // Check if it's a GraphQL request - skip similar matching for GraphQL
@@ -287,7 +294,9 @@ class MockifyerClass {
287
294
  continue; // Required parameter differs, skip this mock
288
295
  }
289
296
  }
290
- similarMatch = { mockData, filename: file, filePath };
297
+ if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
298
+ similarMatch = { mockData, filename: file, filePath };
299
+ }
291
300
  }
292
301
  }
293
302
  catch (e) {
@@ -355,7 +364,7 @@ class MockifyerClass {
355
364
  'x-mockifyer-filepath': filePath
356
365
  };
357
366
  const mockResponse = {
358
- data: mockData.response.data,
367
+ data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
359
368
  status: mockData.response.status,
360
369
  statusText: 'OK',
361
370
  headers: responseHeaders,
@@ -477,8 +486,9 @@ class MockifyerClass {
477
486
  if (isMocked || isLimitReached) {
478
487
  return response;
479
488
  }
480
- // Only save if recordMode is enabled
481
- if (this.config.recordMode) {
489
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
490
+ // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
491
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
482
492
  await this.saveResponse(response);
483
493
  }
484
494
  return response;
@@ -495,6 +505,11 @@ class MockifyerClass {
495
505
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
496
506
  return;
497
507
  }
508
+ // If using a proxy for upstream calls, do not save locally.
509
+ // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
510
+ if (this.config.proxy?.baseUrl) {
511
+ return;
512
+ }
498
513
  const url = response.config?.url || response.request?.responseURL || response.url || '';
499
514
  if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
500
515
  return;
@@ -599,7 +614,7 @@ class MockifyerClass {
599
614
  const domain = urlParts[0].replace(/\./g, '_');
600
615
  const urlPathPart = urlParts.slice(1).join('_') || 'root';
601
616
  const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
602
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
617
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
603
618
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
604
619
  (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
605
620
  // Check request limit before saving (only if limit is set via env var)
@@ -26,7 +26,10 @@ export interface ReactNativeMockifyerConfig {
26
26
  proxyBaseUrl?: string;
27
27
  /** Optional: force proxy scenario */
28
28
  proxyScenario?: string;
29
- /** Optional: record responses on proxy cache miss (proxy must support recording) */
29
+ /**
30
+ * Optional: record responses on proxy cache miss (proxy must support recording).
31
+ * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
32
+ */
30
33
  proxyRecordOnMiss?: boolean;
31
34
  }
32
35
  /**
@@ -64,7 +64,8 @@ async function loadBundledMockData(bundledDataPath) {
64
64
  * ```
65
65
  */
66
66
  async function setupMockifyerForReactNative(options) {
67
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss = false, } = options;
67
+ const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, } = options;
68
+ const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
68
69
  // Check if Mockifyer is enabled
69
70
  const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
70
71
  if (!isEnabled) {
@@ -103,7 +104,7 @@ async function setupMockifyerForReactNative(options) {
103
104
  recordMode,
104
105
  useGlobalFetch: true,
105
106
  proxy: proxyBaseUrl
106
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
107
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
107
108
  : undefined,
108
109
  ...config,
109
110
  });
@@ -145,7 +146,7 @@ async function setupMockifyerForReactNative(options) {
145
146
  recordMode: false, // Can't record in production builds
146
147
  useGlobalFetch: true,
147
148
  proxy: proxyBaseUrl
148
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
149
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
149
150
  : undefined,
150
151
  ...config,
151
152
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.7",
3
+ "version": "1.8.10",
4
4
  "description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -46,7 +46,7 @@
46
46
  "author": "sgedda",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@sgedda/mockifyer-core": "^1.8.7"
49
+ "@sgedda/mockifyer-core": "^1.8.10"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "^20.11.24",
@@ -7,11 +7,13 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
7
7
  private proxyBaseUrl?: string;
8
8
  private proxyScenario?: string;
9
9
  private proxyRecordOnMiss: boolean;
10
+ private clientId?: string;
10
11
 
11
12
  constructor(config?: {
12
13
  baseUrl?: string;
13
14
  defaultHeaders?: Record<string, string>;
14
15
  proxy?: { baseUrl: string; scenario?: string; recordOnMiss?: boolean };
16
+ clientId?: string;
15
17
  }) {
16
18
  super();
17
19
  this.baseUrl = config?.baseUrl;
@@ -19,6 +21,7 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
19
21
  this.proxyBaseUrl = config?.proxy?.baseUrl;
20
22
  this.proxyScenario = config?.proxy?.scenario;
21
23
  this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
24
+ this.clientId = config?.clientId;
22
25
  }
23
26
 
24
27
  protected async performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>> {
@@ -71,10 +74,14 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
71
74
  const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
72
75
  const proxyResponse = await fetchFn(proxyUrl, {
73
76
  method: 'POST',
74
- headers: { 'content-type': 'application/json' },
77
+ headers: {
78
+ 'content-type': 'application/json',
79
+ ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
80
+ },
75
81
  body: JSON.stringify({
76
82
  url,
77
83
  method: requestConfig.method,
84
+ clientId: this.clientId,
78
85
  headers: (() => {
79
86
  const out: Record<string, string> = {};
80
87
  headers.forEach((value, key) => {
package/src/index.ts CHANGED
@@ -33,7 +33,11 @@ import {
33
33
  TestGenerator,
34
34
  TestGenerationOptions,
35
35
  checkRequestLimit,
36
- shouldExcludeUrl
36
+ prepareMockResponseBody,
37
+ getCurrentDate,
38
+ shouldExcludeUrl,
39
+ mockPassesThroughToRealApi,
40
+ resolveClientId
37
41
  } from '@sgedda/mockifyer-core';
38
42
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
39
43
 
@@ -104,6 +108,9 @@ class MockifyerClass {
104
108
 
105
109
  // Store config BEFORE any modifications
106
110
  this.config = { ...config }; // Create a copy to avoid mutations
111
+
112
+ // Resolve client lane id (env/config/fallback); used for Redis per-client scenario overrides and proxy headers.
113
+ this.config.clientId = resolveClientId(this.config);
107
114
 
108
115
  // Initialize test generator if test generation is enabled
109
116
  if (config.generateTests?.enabled) {
@@ -118,6 +125,7 @@ class MockifyerClass {
118
125
  ...config.databaseProvider.options,
119
126
  mockDataPath:
120
127
  config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
128
+ clientId: this.config.clientId,
121
129
  },
122
130
  };
123
131
  this.databaseProvider = createProvider(config.databaseProvider.type, providerConfig);
@@ -137,7 +145,8 @@ class MockifyerClass {
137
145
  this.httpClient = new FetchHTTPClient({
138
146
  baseUrl: config.baseUrl,
139
147
  defaultHeaders: config.defaultHeaders,
140
- proxy: config.proxy
148
+ proxy: config.proxy,
149
+ clientId: this.config.clientId,
141
150
  });
142
151
 
143
152
  if(!config.recordSameEndpoints) {
@@ -243,7 +252,7 @@ class MockifyerClass {
243
252
  return undefined;
244
253
  }
245
254
 
246
- const currentScenario = getCurrentScenario(resolvedMockDataPath);
255
+ const currentScenario = getCurrentScenario(resolvedMockDataPath, this.config.clientId);
247
256
  const scenarioPath = getScenarioFolderPath(resolvedMockDataPath, currentScenario);
248
257
 
249
258
  if (!fs.existsSync(scenarioPath)) {
@@ -271,8 +280,11 @@ class MockifyerClass {
271
280
  const mockKey = this.generateRequestKey(mockData.request);
272
281
 
273
282
  if (mockKey === requestKey) {
274
- exactMatch = { mockData, filename: file, filePath };
275
- break;
283
+ if (!mockPassesThroughToRealApi(mockData)) {
284
+ exactMatch = { mockData, filename: file, filePath };
285
+ break;
286
+ }
287
+ continue;
276
288
  }
277
289
 
278
290
  if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
@@ -348,7 +360,9 @@ class MockifyerClass {
348
360
  }
349
361
  }
350
362
 
351
- similarMatch = { mockData, filename: file, filePath };
363
+ if (!mockPassesThroughToRealApi(mockData)) {
364
+ similarMatch = { mockData, filename: file, filePath };
365
+ }
352
366
  }
353
367
  } catch (e) {
354
368
  continue;
@@ -427,7 +441,7 @@ class MockifyerClass {
427
441
  };
428
442
 
429
443
  const mockResponse = {
430
- data: mockData.response.data,
444
+ data: prepareMockResponseBody(mockData, getCurrentDate),
431
445
  status: mockData.response.status,
432
446
  statusText: 'OK',
433
447
  headers: responseHeaders,
@@ -570,8 +584,9 @@ class MockifyerClass {
570
584
  return response;
571
585
  }
572
586
 
573
- // Only save if recordMode is enabled
574
- if (this.config.recordMode) {
587
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
588
+ // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
589
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
575
590
  await this.saveResponse(response);
576
591
  }
577
592
  return response;
@@ -591,6 +606,12 @@ class MockifyerClass {
591
606
  if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
592
607
  return;
593
608
  }
609
+
610
+ // If using a proxy for upstream calls, do not save locally.
611
+ // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
612
+ if (this.config.proxy?.baseUrl) {
613
+ return;
614
+ }
594
615
 
595
616
  const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
596
617
  if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
@@ -706,7 +727,7 @@ class MockifyerClass {
706
727
  const domain = urlParts[0].replace(/\./g, '_');
707
728
  const urlPathPart = urlParts.slice(1).join('_') || 'root';
708
729
  const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
709
- const currentScenario = getCurrentScenario(this.config.mockDataPath);
730
+ const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
710
731
  const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
711
732
  ensureScenarioFolder(this.config.mockDataPath, currentScenario);
712
733
 
@@ -32,7 +32,10 @@ export interface ReactNativeMockifyerConfig {
32
32
  proxyBaseUrl?: string;
33
33
  /** Optional: force proxy scenario */
34
34
  proxyScenario?: string;
35
- /** Optional: record responses on proxy cache miss (proxy must support recording) */
35
+ /**
36
+ * Optional: record responses on proxy cache miss (proxy must support recording).
37
+ * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
38
+ */
36
39
  proxyRecordOnMiss?: boolean;
37
40
  }
38
41
 
@@ -104,9 +107,11 @@ export async function setupMockifyerForReactNative(
104
107
  config = {},
105
108
  proxyBaseUrl,
106
109
  proxyScenario,
107
- proxyRecordOnMiss = false,
110
+ proxyRecordOnMiss,
108
111
  } = options;
109
112
 
113
+ const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
114
+
110
115
  // Check if Mockifyer is enabled
111
116
  const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
112
117
  if (!isEnabled) {
@@ -149,7 +154,7 @@ export async function setupMockifyerForReactNative(
149
154
  recordMode,
150
155
  useGlobalFetch: true,
151
156
  proxy: proxyBaseUrl
152
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
157
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
153
158
  : undefined,
154
159
  ...config,
155
160
  });
@@ -198,7 +203,7 @@ export async function setupMockifyerForReactNative(
198
203
  recordMode: false, // Can't record in production builds
199
204
  useGlobalFetch: true,
200
205
  proxy: proxyBaseUrl
201
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
206
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
202
207
  : undefined,
203
208
  ...config,
204
209
  });