@sgedda/mockifyer-fetch 1.7.0
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.
- package/METRO_CONFIG.md +97 -0
- package/dist/clients/fetch-client.d.ts +13 -0
- package/dist/clients/fetch-client.js +75 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1106 -0
- package/dist/metro-config.d.ts +50 -0
- package/dist/metro-config.js +90 -0
- package/dist/metro-sync-middleware.d.ts +57 -0
- package/dist/metro-sync-middleware.js +483 -0
- package/dist/react-native.d.ts +44 -0
- package/dist/react-native.js +140 -0
- package/dist/test-generation-hook.d.ts +30 -0
- package/dist/test-generation-hook.js +138 -0
- package/metro-polyfills/empty-module.js +5 -0
- package/package.json +57 -0
- package/src/clients/fetch-client.ts +87 -0
- package/src/index.ts +1271 -0
- package/src/metro-config.ts +115 -0
- package/src/metro-sync-middleware.ts +560 -0
- package/src/react-native.ts +184 -0
- package/src/test-generation-hook.ts +146 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React Native/Expo Helper Functions
|
|
3
|
+
*
|
|
4
|
+
* Simplified setup for React Native applications with automatic
|
|
5
|
+
* conditional provider selection (FileSystem in dev, Memory in prod)
|
|
6
|
+
*/
|
|
7
|
+
import { setupMockifyer } from './index';
|
|
8
|
+
import { HTTPClient } from '@sgedda/mockifyer-core';
|
|
9
|
+
export interface MockifyerInstance extends HTTPClient {
|
|
10
|
+
reloadMockData: () => void;
|
|
11
|
+
clearStaleCacheEntries: () => number;
|
|
12
|
+
clearAllMocks: () => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface ReactNativeMockifyerConfig {
|
|
15
|
+
/** Whether we're in development mode (determines which provider to use) */
|
|
16
|
+
isDev: boolean;
|
|
17
|
+
/** Path to mock data directory (used in development) */
|
|
18
|
+
mockDataPath?: string;
|
|
19
|
+
/** Path to bundled mock data file (used in production) */
|
|
20
|
+
bundledDataPath?: string;
|
|
21
|
+
/** Enable recording mode (development only) */
|
|
22
|
+
recordMode?: boolean;
|
|
23
|
+
/** Additional Mockifyer config options */
|
|
24
|
+
config?: Partial<Parameters<typeof setupMockifyer>[0]>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Setup Mockifyer for React Native/Expo with automatic conditional provider selection
|
|
28
|
+
*
|
|
29
|
+
* - Development (isDev === true): Uses Expo FileSystem provider - can record mocks
|
|
30
|
+
* - Production (isDev === false): Uses Memory provider with bundled TypeScript file
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
|
|
35
|
+
*
|
|
36
|
+
* await setupMockifyerForReactNative({
|
|
37
|
+
* isDev: __DEV__, // Pass React Native's __DEV__ variable
|
|
38
|
+
* mockDataPath: 'mock-data',
|
|
39
|
+
* bundledDataPath: './assets/mock-data',
|
|
40
|
+
* recordMode: process.env.MOCKIFYER_RECORD === 'true',
|
|
41
|
+
* });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<MockifyerInstance | null>;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* React Native/Expo Helper Functions
|
|
4
|
+
*
|
|
5
|
+
* Simplified setup for React Native applications with automatic
|
|
6
|
+
* conditional provider selection (FileSystem in dev, Memory in prod)
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
|
|
10
|
+
const index_1 = require("./index");
|
|
11
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
12
|
+
// Lazy load bundled data (only used in production builds)
|
|
13
|
+
let bundledMockData = null;
|
|
14
|
+
/**
|
|
15
|
+
* Load bundled mock data from a TypeScript/JavaScript module
|
|
16
|
+
*
|
|
17
|
+
* Note: For React Native/Metro, we need to handle dynamic imports differently
|
|
18
|
+
* Metro doesn't support dynamic require() with variables, so we use a workaround
|
|
19
|
+
*/
|
|
20
|
+
async function loadBundledMockData(bundledDataPath) {
|
|
21
|
+
if (bundledMockData) {
|
|
22
|
+
return bundledMockData;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
// Metro bundler doesn't support dynamic require() with variables
|
|
26
|
+
// We use eval with a fully constructed string to avoid Metro's static analysis
|
|
27
|
+
// This bypasses Metro's static analysis completely
|
|
28
|
+
const r = 'r';
|
|
29
|
+
const e = 'e';
|
|
30
|
+
const q = 'q';
|
|
31
|
+
const u = 'u';
|
|
32
|
+
const i = 'i';
|
|
33
|
+
const req = r + e + q + u + i + r + e;
|
|
34
|
+
// eslint-disable-next-line no-eval
|
|
35
|
+
const module = eval(`${req}(${JSON.stringify(bundledDataPath)})`);
|
|
36
|
+
const data = Array.isArray(module.mockData)
|
|
37
|
+
? module.mockData
|
|
38
|
+
: [module.mockData];
|
|
39
|
+
bundledMockData = data;
|
|
40
|
+
return data;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
console.warn('[Mockifyer] Could not load bundled mock data:', error);
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Setup Mockifyer for React Native/Expo with automatic conditional provider selection
|
|
49
|
+
*
|
|
50
|
+
* - Development (isDev === true): Uses Expo FileSystem provider - can record mocks
|
|
51
|
+
* - Production (isDev === false): Uses Memory provider with bundled TypeScript file
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
|
|
56
|
+
*
|
|
57
|
+
* await setupMockifyerForReactNative({
|
|
58
|
+
* isDev: __DEV__, // Pass React Native's __DEV__ variable
|
|
59
|
+
* mockDataPath: 'mock-data',
|
|
60
|
+
* bundledDataPath: './assets/mock-data',
|
|
61
|
+
* recordMode: process.env.MOCKIFYER_RECORD === 'true',
|
|
62
|
+
* });
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
async function setupMockifyerForReactNative(options) {
|
|
66
|
+
const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, } = options;
|
|
67
|
+
// Check if Mockifyer is enabled
|
|
68
|
+
const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
|
|
69
|
+
if (!isEnabled) {
|
|
70
|
+
console.log('[Mockifyer] Disabled');
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
if (isDev === true) {
|
|
74
|
+
// DEVELOPMENT MODE (React Native app running in dev)
|
|
75
|
+
// Use Hybrid provider - saves to both device AND project folder simultaneously
|
|
76
|
+
// Files are immediately available in project folder (no polling needed)
|
|
77
|
+
// Note: The provider's initialize() is async and will be handled by the provider methods
|
|
78
|
+
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
79
|
+
// Merge database provider config from options if provided
|
|
80
|
+
const baseDatabaseProvider = {
|
|
81
|
+
type: 'hybrid',
|
|
82
|
+
path: mockDataPath,
|
|
83
|
+
options: {
|
|
84
|
+
metroPort,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
// Merge with config.databaseProvider if provided
|
|
88
|
+
const databaseProviderConfig = config.databaseProvider
|
|
89
|
+
? {
|
|
90
|
+
...baseDatabaseProvider,
|
|
91
|
+
...config.databaseProvider,
|
|
92
|
+
options: {
|
|
93
|
+
...baseDatabaseProvider.options,
|
|
94
|
+
...(config.databaseProvider.options || {}),
|
|
95
|
+
metroPort, // Always ensure metroPort is set
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
: baseDatabaseProvider;
|
|
99
|
+
const instance = (0, index_1.setupMockifyer)({
|
|
100
|
+
mockDataPath,
|
|
101
|
+
databaseProvider: databaseProviderConfig,
|
|
102
|
+
recordMode,
|
|
103
|
+
useGlobalFetch: true,
|
|
104
|
+
...config,
|
|
105
|
+
});
|
|
106
|
+
console.log('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
107
|
+
console.log(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
|
|
108
|
+
if (recordMode) {
|
|
109
|
+
console.log('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
110
|
+
}
|
|
111
|
+
return instance;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
// PRODUCTION BUILD MODE
|
|
115
|
+
// Use Memory provider with bundled TypeScript file
|
|
116
|
+
const provider = new mockifyer_core_1.MemoryProvider({});
|
|
117
|
+
provider.initialize();
|
|
118
|
+
// Load bundled mock data
|
|
119
|
+
const mockDataArray = await loadBundledMockData(bundledDataPath);
|
|
120
|
+
if (mockDataArray.length === 0) {
|
|
121
|
+
console.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
// Pre-load all mocks into memory
|
|
125
|
+
for (const mockData of mockDataArray) {
|
|
126
|
+
provider.save(mockData);
|
|
127
|
+
}
|
|
128
|
+
const instance = (0, index_1.setupMockifyer)({
|
|
129
|
+
mockDataPath: './mock-data', // Not used with memory provider
|
|
130
|
+
databaseProvider: {
|
|
131
|
+
type: 'memory',
|
|
132
|
+
},
|
|
133
|
+
recordMode: false, // Can't record in production builds
|
|
134
|
+
useGlobalFetch: true,
|
|
135
|
+
...config,
|
|
136
|
+
});
|
|
137
|
+
console.log(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
|
|
138
|
+
return instance;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test generation hook for Metro sync middleware
|
|
3
|
+
*
|
|
4
|
+
* This is a separate module that can be used as a callback with the Metro sync middleware
|
|
5
|
+
* to generate tests when mocks are saved. This keeps test generation separate from the
|
|
6
|
+
* core sync functionality.
|
|
7
|
+
*/
|
|
8
|
+
import { MockData } from '@sgedda/mockifyer-core';
|
|
9
|
+
export interface TestGenerationHookOptions {
|
|
10
|
+
/** Project root directory */
|
|
11
|
+
projectRoot: string;
|
|
12
|
+
/** Test framework to use */
|
|
13
|
+
framework?: 'jest' | 'vitest' | 'mocha';
|
|
14
|
+
/** Output path for generated tests */
|
|
15
|
+
outputPath?: string;
|
|
16
|
+
/** Test file naming pattern */
|
|
17
|
+
testPattern?: string;
|
|
18
|
+
/** Include setup code in generated tests */
|
|
19
|
+
includeSetup?: boolean;
|
|
20
|
+
/** Group tests by: 'endpoint', 'scenario', or 'file' */
|
|
21
|
+
groupBy?: 'endpoint' | 'scenario' | 'file';
|
|
22
|
+
/** HTTP client type */
|
|
23
|
+
httpClientType?: 'fetch' | 'axios';
|
|
24
|
+
/** If true, only generate one test per endpoint */
|
|
25
|
+
uniqueTestsPerEndpoint?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates a test generation hook function that can be used with Metro sync middleware
|
|
29
|
+
*/
|
|
30
|
+
export declare function createTestGenerationHook(options: TestGenerationHookOptions): (mockData: MockData, filePath: string) => Promise<void>;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Test generation hook for Metro sync middleware
|
|
4
|
+
*
|
|
5
|
+
* This is a separate module that can be used as a callback with the Metro sync middleware
|
|
6
|
+
* to generate tests when mocks are saved. This keeps test generation separate from the
|
|
7
|
+
* core sync functionality.
|
|
8
|
+
*/
|
|
9
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
12
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
13
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
14
|
+
}
|
|
15
|
+
Object.defineProperty(o, k2, desc);
|
|
16
|
+
}) : (function(o, m, k, k2) {
|
|
17
|
+
if (k2 === undefined) k2 = k;
|
|
18
|
+
o[k2] = m[k];
|
|
19
|
+
}));
|
|
20
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
21
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
22
|
+
}) : function(o, v) {
|
|
23
|
+
o["default"] = v;
|
|
24
|
+
});
|
|
25
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
26
|
+
var ownKeys = function(o) {
|
|
27
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
28
|
+
var ar = [];
|
|
29
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
30
|
+
return ar;
|
|
31
|
+
};
|
|
32
|
+
return ownKeys(o);
|
|
33
|
+
};
|
|
34
|
+
return function (mod) {
|
|
35
|
+
if (mod && mod.__esModule) return mod;
|
|
36
|
+
var result = {};
|
|
37
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
38
|
+
__setModuleDefault(result, mod);
|
|
39
|
+
return result;
|
|
40
|
+
};
|
|
41
|
+
})();
|
|
42
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
43
|
+
exports.createTestGenerationHook = createTestGenerationHook;
|
|
44
|
+
const fs = __importStar(require("fs"));
|
|
45
|
+
const path = __importStar(require("path"));
|
|
46
|
+
/**
|
|
47
|
+
* Creates a test generation hook function that can be used with Metro sync middleware
|
|
48
|
+
*/
|
|
49
|
+
function createTestGenerationHook(options) {
|
|
50
|
+
const { projectRoot, framework = 'jest', outputPath = './tests/generated', testPattern = '{endpoint}.test.ts', includeSetup = true, groupBy = 'endpoint', httpClientType = 'fetch', uniqueTestsPerEndpoint = false, } = options;
|
|
51
|
+
return async (mockData, filePath) => {
|
|
52
|
+
try {
|
|
53
|
+
// Try to require TestGenerator from mockifyer-core
|
|
54
|
+
let TestGeneratorClass;
|
|
55
|
+
try {
|
|
56
|
+
let mockifyerCore;
|
|
57
|
+
try {
|
|
58
|
+
mockifyerCore = require('@sgedda/mockifyer-core');
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
// Fallback: try relative path (for local file: dependencies)
|
|
62
|
+
const corePath = path.join(projectRoot, '../../packages/mockifyer-core/dist/index.js');
|
|
63
|
+
if (fs.existsSync(corePath)) {
|
|
64
|
+
mockifyerCore = require(corePath);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
throw new Error(`Could not find mockifyer-core at ${corePath}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
TestGeneratorClass = mockifyerCore?.TestGenerator;
|
|
71
|
+
if (!TestGeneratorClass) {
|
|
72
|
+
const testGeneratorPath = path.join(projectRoot, '../../packages/mockifyer-core/dist/utils/test-generator.js');
|
|
73
|
+
if (fs.existsSync(testGeneratorPath)) {
|
|
74
|
+
const testGeneratorModule = require(testGeneratorPath);
|
|
75
|
+
TestGeneratorClass = testGeneratorModule.TestGenerator;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${e.message}`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (!TestGeneratorClass) {
|
|
84
|
+
console.log('[MockSync] ⚠️ TestGenerator not available');
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const generator = new TestGeneratorClass();
|
|
88
|
+
const testOptions = {
|
|
89
|
+
framework,
|
|
90
|
+
outputPath,
|
|
91
|
+
testPattern,
|
|
92
|
+
includeSetup,
|
|
93
|
+
groupBy,
|
|
94
|
+
httpClientType,
|
|
95
|
+
uniqueTestsPerEndpoint,
|
|
96
|
+
};
|
|
97
|
+
const testInfo = generator.analyzeMock(mockData, httpClientType);
|
|
98
|
+
const testFilePath = generator.determineTestFilePath(mockData, testOptions);
|
|
99
|
+
const absoluteTestPath = path.resolve(projectRoot, testFilePath);
|
|
100
|
+
const testDir = path.dirname(absoluteTestPath);
|
|
101
|
+
// If uniqueTestsPerEndpoint is enabled, check if a test file already exists
|
|
102
|
+
if (uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
|
|
103
|
+
console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
// Ensure test directory exists
|
|
107
|
+
if (!fs.existsSync(testDir)) {
|
|
108
|
+
fs.mkdirSync(testDir, { recursive: true });
|
|
109
|
+
}
|
|
110
|
+
const testCode = generator.generateTest(mockData, testOptions);
|
|
111
|
+
// Check if test file already exists
|
|
112
|
+
if (fs.existsSync(absoluteTestPath)) {
|
|
113
|
+
const testName = `${testInfo.method} ${testInfo.endpoint}`;
|
|
114
|
+
const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
|
|
115
|
+
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
116
|
+
console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
// Append test to existing file
|
|
120
|
+
const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
|
|
121
|
+
if (testMatch) {
|
|
122
|
+
const newTest = testMatch[0];
|
|
123
|
+
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
124
|
+
fs.writeFileSync(absoluteTestPath, updatedContent);
|
|
125
|
+
console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
// Create new test file
|
|
130
|
+
fs.writeFileSync(absoluteTestPath, testCode);
|
|
131
|
+
console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
console.error(`[MockSync] ❌ Error generating test:`, error);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
+
"version": "1.7.0",
|
|
4
|
+
"description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./react-native": {
|
|
13
|
+
"types": "./dist/react-native.d.ts",
|
|
14
|
+
"default": "./dist/react-native.js"
|
|
15
|
+
},
|
|
16
|
+
"./metro-config": {
|
|
17
|
+
"types": "./dist/metro-config.d.ts",
|
|
18
|
+
"default": "./dist/metro-config.js"
|
|
19
|
+
},
|
|
20
|
+
"./metro-sync-middleware": {
|
|
21
|
+
"types": "./dist/metro-sync-middleware.d.ts",
|
|
22
|
+
"default": "./dist/metro-sync-middleware.js"
|
|
23
|
+
},
|
|
24
|
+
"./test-generation-hook": {
|
|
25
|
+
"types": "./dist/test-generation-hook.d.ts",
|
|
26
|
+
"default": "./dist/test-generation-hook.js"
|
|
27
|
+
},
|
|
28
|
+
"./metro-polyfills/empty-module": {
|
|
29
|
+
"default": "./metro-polyfills/empty-module.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsc",
|
|
34
|
+
"watch": "tsc --watch"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"mock",
|
|
38
|
+
"api",
|
|
39
|
+
"testing",
|
|
40
|
+
"http",
|
|
41
|
+
"intercept",
|
|
42
|
+
"fetch"
|
|
43
|
+
],
|
|
44
|
+
"author": "sgedda",
|
|
45
|
+
"license": "MIT",
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@sgedda/mockifyer-core": "^1.7.0"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"repository": {
|
|
53
|
+
"type": "git",
|
|
54
|
+
"url": "git+https://github.com/sgedda/mockifyer.git"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { BaseHTTPClient } from '@sgedda/mockifyer-core';
|
|
2
|
+
import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
|
|
3
|
+
|
|
4
|
+
export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
5
|
+
private baseUrl?: string;
|
|
6
|
+
private defaultHeaders: Record<string, string>;
|
|
7
|
+
|
|
8
|
+
constructor(config?: { baseUrl?: string; defaultHeaders?: Record<string, string> }) {
|
|
9
|
+
super();
|
|
10
|
+
this.baseUrl = config?.baseUrl;
|
|
11
|
+
this.defaultHeaders = config?.defaultHeaders || {};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
protected async performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>> {
|
|
15
|
+
// Check if this is a mock response (set by Mockifyer interceptor)
|
|
16
|
+
if ((config as any).__mockResponse) {
|
|
17
|
+
return (config as any).__mockResponse;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
let url = this.baseUrl ? new URL(config.url || '', this.baseUrl).toString() : config.url;
|
|
21
|
+
if (!url) {
|
|
22
|
+
throw new Error('URL is required');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Handle query parameters (params) - append them to the URL
|
|
26
|
+
if (config.params && Object.keys(config.params).length > 0) {
|
|
27
|
+
try {
|
|
28
|
+
const urlObj = new URL(url);
|
|
29
|
+
Object.entries(config.params).forEach(([key, value]) => {
|
|
30
|
+
if (value !== undefined && value !== null) {
|
|
31
|
+
urlObj.searchParams.append(key, String(value));
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
url = urlObj.toString();
|
|
35
|
+
} catch (error) {
|
|
36
|
+
console.error('[FetchHTTPClient] Error adding params to URL:', error);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const headers = new Headers({
|
|
42
|
+
...this.defaultHeaders,
|
|
43
|
+
...config.headers
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const requestConfig: RequestInit = {
|
|
47
|
+
method: config.method || 'GET',
|
|
48
|
+
headers,
|
|
49
|
+
body: config.data ? JSON.stringify(config.data) : undefined
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Use original fetch if available (when global fetch is patched), otherwise use global fetch
|
|
53
|
+
// CRITICAL: Always use _originalFetch if available to prevent infinite loops
|
|
54
|
+
const fetchFn = (this as any)._originalFetch || fetch;
|
|
55
|
+
if (!(this as any)._originalFetch) {
|
|
56
|
+
console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const response = await fetchFn(url, requestConfig);
|
|
60
|
+
const data = await response.json();
|
|
61
|
+
|
|
62
|
+
// Convert response Headers to Record<string, string>
|
|
63
|
+
const responseHeaders: Record<string, string> = {};
|
|
64
|
+
response.headers.forEach((value: string, key: string) => {
|
|
65
|
+
responseHeaders[key] = value;
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
data,
|
|
70
|
+
status: response.status,
|
|
71
|
+
statusText: response.statusText,
|
|
72
|
+
headers: responseHeaders,
|
|
73
|
+
config
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
protected getDefaultHeaders(): Record<string, string> {
|
|
78
|
+
return this.defaultHeaders;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
protected getDefaultConfig(): Record<string, any> {
|
|
82
|
+
return {
|
|
83
|
+
baseUrl: this.baseUrl
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|