@sgedda/mockifyer-fetch 1.8.6 → 1.8.8

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.
@@ -3,9 +3,17 @@ import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
3
  export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
4
4
  private baseUrl?;
5
5
  private defaultHeaders;
6
+ private proxyBaseUrl?;
7
+ private proxyScenario?;
8
+ private proxyRecordOnMiss;
6
9
  constructor(config?: {
7
10
  baseUrl?: string;
8
11
  defaultHeaders?: Record<string, string>;
12
+ proxy?: {
13
+ baseUrl: string;
14
+ scenario?: string;
15
+ recordOnMiss?: boolean;
16
+ };
9
17
  });
10
18
  protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
11
19
  protected getDefaultHeaders(): Record<string, string>;
@@ -7,6 +7,9 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
7
7
  super();
8
8
  this.baseUrl = config?.baseUrl;
9
9
  this.defaultHeaders = config?.defaultHeaders || {};
10
+ this.proxyBaseUrl = config?.proxy?.baseUrl;
11
+ this.proxyScenario = config?.proxy?.scenario;
12
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
10
13
  }
11
14
  async performRequest(config) {
12
15
  // Check if this is a mock response (set by Mockifyer interceptor)
@@ -48,8 +51,55 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
48
51
  if (!this._originalFetch) {
49
52
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
50
53
  }
54
+ // Proxy mode (e.g. React Native → dashboard → Redis)
55
+ if (this.proxyBaseUrl) {
56
+ const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
57
+ const proxyResponse = await fetchFn(proxyUrl, {
58
+ method: 'POST',
59
+ headers: { 'content-type': 'application/json' },
60
+ body: JSON.stringify({
61
+ url,
62
+ method: requestConfig.method,
63
+ headers: (() => {
64
+ const out = {};
65
+ headers.forEach((value, key) => {
66
+ out[key] = value;
67
+ });
68
+ return out;
69
+ })(),
70
+ body: config.data ?? null,
71
+ scenario: this.proxyScenario,
72
+ record: this.proxyRecordOnMiss,
73
+ }),
74
+ });
75
+ if (!proxyResponse.ok) {
76
+ const txt = await proxyResponse.text();
77
+ throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
78
+ }
79
+ const payload = await proxyResponse.json();
80
+ const data = payload?.response?.data;
81
+ const status = payload?.response?.status ?? 200;
82
+ const responseHeaders = payload?.response?.headers ?? {};
83
+ return {
84
+ data,
85
+ status,
86
+ statusText: String(status),
87
+ headers: responseHeaders,
88
+ config,
89
+ };
90
+ }
51
91
  const response = await fetchFn(url, requestConfig);
52
- const data = await response.json();
92
+ const contentType = response.headers.get('content-type') || '';
93
+ const rawText = await response.text();
94
+ let data = rawText;
95
+ if (contentType.includes('application/json')) {
96
+ try {
97
+ data = JSON.parse(rawText);
98
+ }
99
+ catch {
100
+ data = rawText;
101
+ }
102
+ }
53
103
  // Convert response Headers to Record<string, string>
54
104
  const responseHeaders = {};
55
105
  response.headers.forEach((value, key) => {
@@ -60,7 +110,7 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
60
110
  status: response.status,
61
111
  statusText: response.statusText,
62
112
  headers: responseHeaders,
63
- config
113
+ config,
64
114
  };
65
115
  }
66
116
  getDefaultHeaders() {
package/dist/index.js CHANGED
@@ -111,7 +111,8 @@ class MockifyerClass {
111
111
  // Create fetch HTTP client
112
112
  this.httpClient = new fetch_client_1.FetchHTTPClient({
113
113
  baseUrl: config.baseUrl,
114
- defaultHeaders: config.defaultHeaders
114
+ defaultHeaders: config.defaultHeaders,
115
+ proxy: config.proxy
115
116
  });
116
117
  if (!config.recordSameEndpoints) {
117
118
  this.loadMockData();
@@ -354,7 +355,7 @@ class MockifyerClass {
354
355
  'x-mockifyer-filepath': filePath
355
356
  };
356
357
  const mockResponse = {
357
- data: mockData.response.data,
358
+ data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
358
359
  status: mockData.response.status,
359
360
  statusText: 'OK',
360
361
  headers: responseHeaders,
@@ -476,8 +477,9 @@ class MockifyerClass {
476
477
  if (isMocked || isLimitReached) {
477
478
  return response;
478
479
  }
479
- // Only save if recordMode is enabled
480
- if (this.config.recordMode) {
480
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
481
+ // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
482
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
481
483
  await this.saveResponse(response);
482
484
  }
483
485
  return response;
@@ -494,6 +496,11 @@ class MockifyerClass {
494
496
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
495
497
  return;
496
498
  }
499
+ // If using a proxy for upstream calls, do not save locally.
500
+ // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
501
+ if (this.config.proxy?.baseUrl) {
502
+ return;
503
+ }
497
504
  const url = response.config?.url || response.request?.responseURL || response.url || '';
498
505
  if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
499
506
  return;
@@ -22,6 +22,15 @@ export interface ReactNativeMockifyerConfig {
22
22
  recordMode?: boolean;
23
23
  /** Additional Mockifyer config options */
24
24
  config?: Partial<Parameters<typeof setupMockifyer>[0]>;
25
+ /** Optional: route real network calls through a proxy service (e.g. mockifyer-dashboard in Redis mode) */
26
+ proxyBaseUrl?: string;
27
+ /** Optional: force proxy scenario */
28
+ proxyScenario?: string;
29
+ /**
30
+ * Optional: record responses on proxy cache miss (proxy must support recording).
31
+ * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
32
+ */
33
+ proxyRecordOnMiss?: boolean;
25
34
  }
26
35
  /**
27
36
  * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
@@ -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 = {}, } = 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) {
@@ -102,6 +103,9 @@ async function setupMockifyerForReactNative(options) {
102
103
  databaseProvider: databaseProviderConfig,
103
104
  recordMode,
104
105
  useGlobalFetch: true,
106
+ proxy: proxyBaseUrl
107
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
108
+ : undefined,
105
109
  ...config,
106
110
  });
107
111
  mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
@@ -141,6 +145,9 @@ async function setupMockifyerForReactNative(options) {
141
145
  },
142
146
  recordMode: false, // Can't record in production builds
143
147
  useGlobalFetch: true,
148
+ proxy: proxyBaseUrl
149
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
150
+ : undefined,
144
151
  ...config,
145
152
  });
146
153
  mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.6",
3
+ "version": "1.8.8",
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.6"
49
+ "@sgedda/mockifyer-core": "^1.8.8"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "^20.11.24",
@@ -4,11 +4,21 @@ import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
4
4
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
5
5
  private baseUrl?: string;
6
6
  private defaultHeaders: Record<string, string>;
7
+ private proxyBaseUrl?: string;
8
+ private proxyScenario?: string;
9
+ private proxyRecordOnMiss: boolean;
7
10
 
8
- constructor(config?: { baseUrl?: string; defaultHeaders?: Record<string, string> }) {
11
+ constructor(config?: {
12
+ baseUrl?: string;
13
+ defaultHeaders?: Record<string, string>;
14
+ proxy?: { baseUrl: string; scenario?: string; recordOnMiss?: boolean };
15
+ }) {
9
16
  super();
10
17
  this.baseUrl = config?.baseUrl;
11
18
  this.defaultHeaders = config?.defaultHeaders || {};
19
+ this.proxyBaseUrl = config?.proxy?.baseUrl;
20
+ this.proxyScenario = config?.proxy?.scenario;
21
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
12
22
  }
13
23
 
14
24
  protected async performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>> {
@@ -56,8 +66,56 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
56
66
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
57
67
  }
58
68
 
69
+ // Proxy mode (e.g. React Native → dashboard → Redis)
70
+ if (this.proxyBaseUrl) {
71
+ const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
72
+ const proxyResponse = await fetchFn(proxyUrl, {
73
+ method: 'POST',
74
+ headers: { 'content-type': 'application/json' },
75
+ body: JSON.stringify({
76
+ url,
77
+ method: requestConfig.method,
78
+ headers: (() => {
79
+ const out: Record<string, string> = {};
80
+ headers.forEach((value, key) => {
81
+ out[key] = value;
82
+ });
83
+ return out;
84
+ })(),
85
+ body: config.data ?? null,
86
+ scenario: this.proxyScenario,
87
+ record: this.proxyRecordOnMiss,
88
+ }),
89
+ });
90
+ if (!proxyResponse.ok) {
91
+ const txt = await proxyResponse.text();
92
+ throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
93
+ }
94
+ const payload = await proxyResponse.json();
95
+ const data = payload?.response?.data;
96
+ const status = payload?.response?.status ?? 200;
97
+ const responseHeaders: Record<string, string> = payload?.response?.headers ?? {};
98
+
99
+ return {
100
+ data,
101
+ status,
102
+ statusText: String(status),
103
+ headers: responseHeaders,
104
+ config,
105
+ };
106
+ }
107
+
59
108
  const response = await fetchFn(url, requestConfig);
60
- const data = await response.json();
109
+ const contentType = response.headers.get('content-type') || '';
110
+ const rawText = await response.text();
111
+ let data: any = rawText;
112
+ if (contentType.includes('application/json')) {
113
+ try {
114
+ data = JSON.parse(rawText);
115
+ } catch {
116
+ data = rawText;
117
+ }
118
+ }
61
119
 
62
120
  // Convert response Headers to Record<string, string>
63
121
  const responseHeaders: Record<string, string> = {};
@@ -70,7 +128,7 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
70
128
  status: response.status,
71
129
  statusText: response.statusText,
72
130
  headers: responseHeaders,
73
- config
131
+ config,
74
132
  };
75
133
  }
76
134
 
package/src/index.ts CHANGED
@@ -33,6 +33,8 @@ import {
33
33
  TestGenerator,
34
34
  TestGenerationOptions,
35
35
  checkRequestLimit,
36
+ prepareMockResponseBody,
37
+ getCurrentDate,
36
38
  shouldExcludeUrl
37
39
  } from '@sgedda/mockifyer-core';
38
40
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
@@ -136,7 +138,8 @@ class MockifyerClass {
136
138
  // Create fetch HTTP client
137
139
  this.httpClient = new FetchHTTPClient({
138
140
  baseUrl: config.baseUrl,
139
- defaultHeaders: config.defaultHeaders
141
+ defaultHeaders: config.defaultHeaders,
142
+ proxy: config.proxy
140
143
  });
141
144
 
142
145
  if(!config.recordSameEndpoints) {
@@ -426,7 +429,7 @@ class MockifyerClass {
426
429
  };
427
430
 
428
431
  const mockResponse = {
429
- data: mockData.response.data,
432
+ data: prepareMockResponseBody(mockData, getCurrentDate),
430
433
  status: mockData.response.status,
431
434
  statusText: 'OK',
432
435
  headers: responseHeaders,
@@ -569,8 +572,9 @@ class MockifyerClass {
569
572
  return response;
570
573
  }
571
574
 
572
- // Only save if recordMode is enabled
573
- if (this.config.recordMode) {
575
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
576
+ // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
577
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
574
578
  await this.saveResponse(response);
575
579
  }
576
580
  return response;
@@ -590,6 +594,12 @@ class MockifyerClass {
590
594
  if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
591
595
  return;
592
596
  }
597
+
598
+ // If using a proxy for upstream calls, do not save locally.
599
+ // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
600
+ if (this.config.proxy?.baseUrl) {
601
+ return;
602
+ }
593
603
 
594
604
  const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
595
605
  if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
@@ -28,6 +28,15 @@ export interface ReactNativeMockifyerConfig {
28
28
  recordMode?: boolean;
29
29
  /** Additional Mockifyer config options */
30
30
  config?: Partial<Parameters<typeof setupMockifyer>[0]>;
31
+ /** Optional: route real network calls through a proxy service (e.g. mockifyer-dashboard in Redis mode) */
32
+ proxyBaseUrl?: string;
33
+ /** Optional: force proxy scenario */
34
+ proxyScenario?: string;
35
+ /**
36
+ * Optional: record responses on proxy cache miss (proxy must support recording).
37
+ * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
38
+ */
39
+ proxyRecordOnMiss?: boolean;
31
40
  }
32
41
 
33
42
  // Lazy load bundled data (only used in production builds)
@@ -96,8 +105,13 @@ export async function setupMockifyerForReactNative(
96
105
  bundledDataPath = './assets/mock-data',
97
106
  recordMode = false,
98
107
  config = {},
108
+ proxyBaseUrl,
109
+ proxyScenario,
110
+ proxyRecordOnMiss,
99
111
  } = options;
100
112
 
113
+ const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
114
+
101
115
  // Check if Mockifyer is enabled
102
116
  const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
103
117
  if (!isEnabled) {
@@ -139,6 +153,9 @@ export async function setupMockifyerForReactNative(
139
153
  databaseProvider: databaseProviderConfig,
140
154
  recordMode,
141
155
  useGlobalFetch: true,
156
+ proxy: proxyBaseUrl
157
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
158
+ : undefined,
142
159
  ...config,
143
160
  });
144
161
 
@@ -185,6 +202,9 @@ export async function setupMockifyerForReactNative(
185
202
  },
186
203
  recordMode: false, // Can't record in production builds
187
204
  useGlobalFetch: true,
205
+ proxy: proxyBaseUrl
206
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
207
+ : undefined,
188
208
  ...config,
189
209
  });
190
210