@sgedda/mockifyer-fetch 1.8.6 → 1.8.7

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();
@@ -22,6 +22,12 @@ 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
+ /** Optional: record responses on proxy cache miss (proxy must support recording) */
30
+ proxyRecordOnMiss?: boolean;
25
31
  }
26
32
  /**
27
33
  * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
@@ -64,7 +64,7 @@ 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 = false, } = options;
68
68
  // Check if Mockifyer is enabled
69
69
  const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
70
70
  if (!isEnabled) {
@@ -102,6 +102,9 @@ async function setupMockifyerForReactNative(options) {
102
102
  databaseProvider: databaseProviderConfig,
103
103
  recordMode,
104
104
  useGlobalFetch: true,
105
+ proxy: proxyBaseUrl
106
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
107
+ : undefined,
105
108
  ...config,
106
109
  });
107
110
  mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
@@ -141,6 +144,9 @@ async function setupMockifyerForReactNative(options) {
141
144
  },
142
145
  recordMode: false, // Can't record in production builds
143
146
  useGlobalFetch: true,
147
+ proxy: proxyBaseUrl
148
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
149
+ : undefined,
144
150
  ...config,
145
151
  });
146
152
  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.7",
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.7"
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
@@ -136,7 +136,8 @@ class MockifyerClass {
136
136
  // Create fetch HTTP client
137
137
  this.httpClient = new FetchHTTPClient({
138
138
  baseUrl: config.baseUrl,
139
- defaultHeaders: config.defaultHeaders
139
+ defaultHeaders: config.defaultHeaders,
140
+ proxy: config.proxy
140
141
  });
141
142
 
142
143
  if(!config.recordSameEndpoints) {
@@ -28,6 +28,12 @@ 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
+ /** Optional: record responses on proxy cache miss (proxy must support recording) */
36
+ proxyRecordOnMiss?: boolean;
31
37
  }
32
38
 
33
39
  // Lazy load bundled data (only used in production builds)
@@ -96,6 +102,9 @@ export async function setupMockifyerForReactNative(
96
102
  bundledDataPath = './assets/mock-data',
97
103
  recordMode = false,
98
104
  config = {},
105
+ proxyBaseUrl,
106
+ proxyScenario,
107
+ proxyRecordOnMiss = false,
99
108
  } = options;
100
109
 
101
110
  // Check if Mockifyer is enabled
@@ -139,6 +148,9 @@ export async function setupMockifyerForReactNative(
139
148
  databaseProvider: databaseProviderConfig,
140
149
  recordMode,
141
150
  useGlobalFetch: true,
151
+ proxy: proxyBaseUrl
152
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
153
+ : undefined,
142
154
  ...config,
143
155
  });
144
156
 
@@ -185,6 +197,9 @@ export async function setupMockifyerForReactNative(
185
197
  },
186
198
  recordMode: false, // Can't record in production builds
187
199
  useGlobalFetch: true,
200
+ proxy: proxyBaseUrl
201
+ ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyRecordOnMiss }
202
+ : undefined,
188
203
  ...config,
189
204
  });
190
205