-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
921 lines (764 loc) · 28.3 KB
/
index.js
File metadata and controls
921 lines (764 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
#!/usr/bin/env node
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs-extra');
const path = require('path');
const net = require('net');
const app = express();
// Parse command line arguments
const args = process.argv.slice(2);
let port = process.env.PORT || 3000;
let mocksDir = process.env.MOCKS_DIR;
// Parse CLI arguments
for (let i = 0; i < args.length; i++) {
if (args[i] === '--port' || args[i] === '-p') {
port = parseInt(args[i + 1]) || port;
i++;
} else if (args[i] === '--mocks-dir' || args[i] === '-d') {
mocksDir = args[i + 1];
i++;
} else if (args[i] === '--help' || args[i] === '-h') {
console.log(`
Mocker Server - A powerful mock server with GUI
Usage: mocker [options]
Options:
-p, --port <number> Port to run the server on (default: 3000)
-d, --mocks-dir <path> Directory to store mock data (default: ./mocks)
-h, --help Show this help message
Environment Variables:
PORT Port to run the server on
MOCKS_DIR Directory to store mock data
Examples:
mocker
mocker --port 8080
mocker --mocks-dir ./api-mocks
MOCKS_DIR=./custom-mocks mocker
`);
process.exit(0);
}
}
const PORT = port;
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static files early in the middleware stack
// Use absolute path to the package directory for npm package usage
app.use(express.static(path.join(__dirname, 'public')));
// Data storage paths - configurable via environment variables or CLI
const MOCKS_DIR = mocksDir || path.join(process.cwd(), 'mocks');
const ENDPOINTS_DIR = path.join(MOCKS_DIR, 'endpoints');
const MOCKS_PUBLIC_DIR = path.join(MOCKS_DIR, 'public');
// Ensure data directories exist
fs.ensureDirSync(MOCKS_DIR);
fs.ensureDirSync(ENDPOINTS_DIR);
fs.ensureDirSync(MOCKS_PUBLIC_DIR);
// Serve static files from mocks/public folder
// This is served after the built-in public folder, so built-in files take precedence
app.use(express.static(MOCKS_PUBLIC_DIR));
// Settings storage
let serverSettings = {
responseDelay: 0,
corsEnabled: true,
autoReload: true,
logLevel: 'info'
};
// Function to check if port is available
const isPortAvailable = (port) => {
return new Promise((resolve) => {
const server = net.createServer();
server.listen(port, () => {
server.once('close', () => {
resolve(true);
});
server.close();
});
server.on('error', () => {
resolve(false);
});
});
};
// Helper functions
const encodeQueryParams = (queryString) => {
// Encode query parameters for filesystem using base64
if (!queryString) return '';
return Buffer.from(queryString).toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const decodeQueryParams = (encoded) => {
// Decode filesystem name back to query string
if (!encoded || !encoded.startsWith('__QUERY__')) return '';
const queryPart = encoded.replace('__QUERY__', '');
try {
const decoded = Buffer.from(
queryPart.replace(/-/g, '+').replace(/_/g, '/'),
'base64'
).toString();
// Ensure it starts with ? if it's not empty
return decoded ? (decoded.startsWith('?') ? decoded : `?${decoded}`) : '';
} catch {
return '';
}
};
const getEndpointDirPath = (endpointPath) => {
// Split path and query string
const [pathPart, queryPart] = endpointPath.split('?');
const cleanPath = pathPart.replace(/^\/+|\/+$/g, ''); // Remove leading/trailing slashes
// Handle dynamic paths by replacing {param} with __param__ for directory structure
const dynamicPath = cleanPath.replace(/\{[^}]+\}/g, (match) => {
const paramName = match.slice(1, -1); // Remove { and }
return `__${paramName}__`;
});
const pathSegments = dynamicPath ? dynamicPath.split('/') : [];
// Add query params as a directory segment if they exist
if (queryPart) {
const encodedQuery = encodeQueryParams(queryPart);
if (encodedQuery) {
pathSegments.push(`__QUERY__${encodedQuery}`);
}
}
return path.join(ENDPOINTS_DIR, ...pathSegments);
};
const getEndpointFilePath = (endpointPath, method, statusCode, name) => {
const dirPath = getEndpointDirPath(endpointPath);
const fileName = `${method.toLowerCase()}.${statusCode}.${name}.json`;
return path.join(dirPath, fileName);
};
const loadEndpoints = () => {
try {
const endpointMap = new Map();
const loadFromDirectory = (dirPath, currentPath = '') => {
if (!fs.existsSync(dirPath)) return;
const items = fs.readdirSync(dirPath);
for (const item of items) {
const itemPath = path.join(dirPath, item);
const stat = fs.statSync(itemPath);
if (stat.isDirectory()) {
// Check if this is a query parameter directory
let newPath;
if (item.startsWith('__QUERY__')) {
// Decode query params and append to path
const queryString = decodeQueryParams(item);
newPath = currentPath ? `${currentPath}${queryString}` : queryString;
} else {
// Regular directory
newPath = currentPath ? `${currentPath}/${item}` : item;
}
loadFromDirectory(itemPath, newPath);
} else if (item.endsWith('.json')) {
// Check if this is a selected response file
if (item.endsWith('.selected.json')) {
const method = item.replace('.selected.json', '').toUpperCase();
// Convert directory structure back to original path format
// Handle paths with query strings - split path and query
let pathPart = currentPath || '';
let queryPart = '';
if (pathPart.includes('?')) {
const parts = pathPart.split('?');
pathPart = parts[0];
queryPart = '?' + parts.slice(1).join('?');
}
// Handle dynamic path segments (only in path part, not query)
pathPart = pathPart.replace(/__([^_]+)__/g, '{$1}');
// Ensure path starts with / if it doesn't already
if (pathPart && !pathPart.startsWith('/')) {
pathPart = `/${pathPart}`;
}
// Reconstruct full path with query string
const fullPath = pathPart + queryPart;
// Create or update endpoint
const endpointKey = `${method}|${fullPath}`;
if (!endpointMap.has(endpointKey)) {
endpointMap.set(endpointKey, {
path: fullPath,
method: method,
responses: [],
selectedResponseName: null
});
}
try {
const selectedData = fs.readJsonSync(itemPath);
const endpoint = endpointMap.get(endpointKey);
endpoint.selectedResponseName = selectedData.selectedResponseName;
} catch (e) {
// Ignore errors reading selected file
}
} else {
// Parse filename: method.statusCode.name.json
const filename = item.replace('.json', '');
const parts = filename.split('.');
if (parts.length >= 3) {
const method = parts[0].toUpperCase();
const statusCode = parseInt(parts[1]);
const name = parts.slice(2).join('.');
// Convert directory structure back to original path format
// Handle paths with query strings - split path and query
let pathPart = currentPath || '';
let queryPart = '';
if (pathPart.includes('?')) {
const parts = pathPart.split('?');
pathPart = parts[0];
queryPart = '?' + parts.slice(1).join('?');
}
// Handle dynamic path segments (only in path part, not query)
pathPart = pathPart.replace(/__([^_]+)__/g, '{$1}');
// Ensure path starts with / if it doesn't already
if (pathPart && !pathPart.startsWith('/')) {
pathPart = `/${pathPart}`;
}
// Reconstruct full path with query string
const fullPath = pathPart + queryPart;
// Load response body
const responseBody = fs.readJsonSync(itemPath);
// Create or update endpoint
const endpointKey = `${method}|${fullPath}`;
if (!endpointMap.has(endpointKey)) {
endpointMap.set(endpointKey, {
path: fullPath,
method: method,
responses: [],
selectedResponseName: null
});
}
const endpoint = endpointMap.get(endpointKey);
endpoint.responses.push({
name: name,
statusCode: statusCode,
body: responseBody,
isDefault: ['Success', 'Error', 'Empty'].includes(name)
});
}
}
}
}
};
loadFromDirectory(ENDPOINTS_DIR);
return Array.from(endpointMap.values());
} catch (error) {
console.error('Error loading endpoints:', error);
return [];
}
};
const saveResponse = (endpointPath, method, statusCode, name, body) => {
try {
const filePath = getEndpointFilePath(endpointPath, method, statusCode, name);
const dirPath = path.dirname(filePath);
// Ensure directory exists
fs.ensureDirSync(dirPath);
fs.writeJsonSync(filePath, body, { spaces: 2 });
return true;
} catch (error) {
console.error('Error saving response:', error);
return false;
}
};
const deleteResponseFile = (endpointPath, method, statusCode, name) => {
try {
const filePath = getEndpointFilePath(endpointPath, method, statusCode, name);
if (fs.existsSync(filePath)) {
fs.removeSync(filePath);
// Clean up empty directories
const dirPath = path.dirname(filePath);
try {
if (fs.readdirSync(dirPath).length === 0) {
fs.removeSync(dirPath);
}
} catch (e) {
// Directory not empty or other error, ignore
}
return true;
}
return false;
} catch (error) {
console.error('Error deleting response file:', error);
return false;
}
};
const deleteAllEndpointFiles = (endpointPath, method) => {
try {
const dirPath = getEndpointDirPath(endpointPath);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file.startsWith(`${method.toLowerCase()}.`) && file.endsWith('.json')) {
fs.removeSync(path.join(dirPath, file));
}
}
// Clean up empty directory
try {
if (fs.readdirSync(dirPath).length === 0) {
fs.removeSync(dirPath);
}
} catch (e) {
// Directory not empty or other error, ignore
}
}
return true;
} catch (error) {
console.error('Error deleting endpoint files:', error);
return false;
}
};
// API Routes
// Helper functions for URL-safe base64 encoding/decoding
const encodeEndpointId = (method, path) => {
return Buffer.from(`${method}|${path}`)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const decodeEndpointId = (id) => {
try {
// Add padding if needed
let base64 = id.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
return Buffer.from(base64, 'base64').toString();
} catch (error) {
return null;
}
};
const findEndpointById = (endpoints, id) => {
const decoded = decodeEndpointId(id);
if (!decoded) {
return null;
}
const [method, path] = decoded.split('|');
return endpoints.find(ep => ep.method === method && ep.path === path) || null;
};
// Get all endpoints
app.get('/api/endpoints', (req, res) => {
const endpoints = loadEndpoints();
// Add ID field for frontend compatibility
const endpointsWithIds = endpoints.map(endpoint => ({
...endpoint,
id: encodeEndpointId(endpoint.method, endpoint.path)
}));
res.json(endpointsWithIds);
});
// Get single endpoint
app.get('/api/endpoints/:id', (req, res) => {
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
// Add ID field for frontend compatibility
const endpointWithId = {
...endpoint,
id: encodeEndpointId(endpoint.method, endpoint.path)
};
res.json(endpointWithId);
});
// Create new endpoint
app.post('/api/endpoints', (req, res) => {
const { path, method } = req.body;
if (!path || !method) {
return res.status(400).json({ error: 'Path and method are required' });
}
const methodUpper = method.toUpperCase();
// Keep query parameters in path - just ensure it starts with a slash
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
// Check if path (without query) is reserved for the application
const pathWithoutQuery = path.split('?')[0];
if (pathWithoutQuery.startsWith('/api/endpoints')) {
return res.status(400).json({
error: 'Path /api/endpoints is reserved for the application and cannot be used'
});
}
// Check if endpoint with same path and method already exists
const existingEndpoints = loadEndpoints();
const existingEndpoint = existingEndpoints.find(ep =>
ep.path === normalizedPath && ep.method === methodUpper
);
if (existingEndpoint) {
return res.status(409).json({
error: `Endpoint with path '${normalizedPath}' and method '${methodUpper}' already exists`
});
}
// Create default response files
const defaultResponses = [
{ name: 'Success', statusCode: 200, body: { message: 'Success' } },
{ name: 'Error', statusCode: 500, body: { error: 'Internal Server Error' } },
{ name: 'Empty', statusCode: 204, body: null }
];
let allSaved = true;
for (const response of defaultResponses) {
if (!saveResponse(normalizedPath, methodUpper, response.statusCode, response.name, response.body)) {
allSaved = false;
break;
}
}
if (allSaved) {
const newEndpoint = {
path: normalizedPath,
method: methodUpper,
responses: defaultResponses.map(r => ({ ...r, isDefault: true })),
selectedResponseName: null
};
// Add ID field for frontend compatibility
const endpointWithId = {
...newEndpoint,
id: encodeEndpointId(newEndpoint.method, newEndpoint.path)
};
res.json(endpointWithId);
} else {
res.status(500).json({ error: 'Failed to save endpoint' });
}
});
// Update endpoint
app.put('/api/endpoints/:id', (req, res) => {
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
const { path: newPath, method: newMethod } = req.body;
// If path or method changed, we need to move files
if ((newPath && newPath !== endpoint.path) || (newMethod && newMethod.toUpperCase() !== endpoint.method)) {
// This is a complex operation - for now, return error
return res.status(400).json({ error: 'Changing endpoint path or method is not supported' });
}
// For now, just return the existing endpoint
const endpointWithId = {
...endpoint,
id: encodeEndpointId(endpoint.method, endpoint.path)
};
res.json(endpointWithId);
});
// Delete endpoint
app.delete('/api/endpoints/:id', (req, res) => {
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
if (deleteAllEndpointFiles(endpoint.path, endpoint.method)) {
res.json({ message: 'Endpoint deleted successfully' });
} else {
res.status(500).json({ error: 'Failed to delete endpoint' });
}
});
// Add response to endpoint
app.post('/api/endpoints/:id/responses', (req, res) => {
const { name, statusCode, body } = req.body;
if (!name || !statusCode) {
return res.status(400).json({ error: 'Name and status code are required' });
}
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
const newResponse = {
name,
statusCode: parseInt(statusCode),
body: body || null,
isDefault: false
};
if (saveResponse(endpoint.path, endpoint.method, newResponse.statusCode, newResponse.name, newResponse.body)) {
res.json(newResponse);
} else {
res.status(500).json({ error: 'Failed to save response' });
}
});
// Update response
app.put('/api/endpoints/:id/responses/:responseName', (req, res) => {
const { name, statusCode, body } = req.body;
const responseName = decodeURIComponent(req.params.responseName);
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
const response = endpoint.responses.find(r => r.name === responseName);
if (!response) {
return res.status(404).json({ error: 'Response not found' });
}
const newName = name || response.name;
const newStatusCode = statusCode ? parseInt(statusCode) : response.statusCode;
const newBody = body !== undefined ? body : response.body;
// Delete old file and create new one
if (deleteResponseFile(endpoint.path, endpoint.method, response.statusCode, response.name) &&
saveResponse(endpoint.path, endpoint.method, newStatusCode, newName, newBody)) {
res.json({
name: newName,
statusCode: newStatusCode,
body: newBody,
isDefault: response.isDefault
});
} else {
res.status(500).json({ error: 'Failed to update response' });
}
});
// Delete response
app.delete('/api/endpoints/:id/responses/:responseName', (req, res) => {
const responseName = decodeURIComponent(req.params.responseName);
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
const response = endpoint.responses.find(r => r.name === responseName);
if (!response) {
return res.status(404).json({ error: 'Response not found' });
}
// Don't allow deletion of default responses
if (response.isDefault) {
return res.status(400).json({ error: 'Cannot delete default responses' });
}
if (deleteResponseFile(endpoint.path, endpoint.method, response.statusCode, response.name)) {
res.json({ message: 'Response deleted successfully' });
} else {
res.status(500).json({ error: 'Failed to delete response' });
}
});
// Set selected response for endpoint
app.put('/api/endpoints/:id/select-response', (req, res) => {
const { responseName } = req.body;
const endpoints = loadEndpoints();
const endpoint = findEndpointById(endpoints, req.params.id);
if (!endpoint) {
return res.status(404).json({ error: 'Endpoint not found' });
}
const response = endpoint.responses.find(r => r.name === responseName);
if (!response) {
return res.status(404).json({ error: 'Response not found' });
}
// Save selected response to a special file
const dirPath = getEndpointDirPath(endpoint.path);
const selectedFile = path.join(dirPath, `${endpoint.method.toLowerCase()}.selected.json`);
try {
fs.ensureDirSync(dirPath);
fs.writeJsonSync(selectedFile, { selectedResponseName: responseName }, { spaces: 2 });
res.json({ message: 'Response selected successfully' });
} catch (error) {
console.error('Error saving selected response:', error);
res.status(500).json({ error: 'Failed to select response' });
}
});
// Settings API
app.get('/api/settings', (req, res) => {
res.json(serverSettings);
});
app.post('/api/settings', (req, res) => {
const { responseDelay, corsEnabled, autoReload, logLevel } = req.body;
// Validate and update settings
if (responseDelay !== undefined) {
serverSettings.responseDelay = Math.max(0, Math.min(10000, parseInt(responseDelay) || 0));
}
if (corsEnabled !== undefined) {
serverSettings.corsEnabled = Boolean(corsEnabled);
}
if (autoReload !== undefined) {
serverSettings.autoReload = Boolean(autoReload);
}
if (logLevel !== undefined && ['error', 'warn', 'info', 'debug'].includes(logLevel)) {
serverSettings.logLevel = logLevel;
}
res.json({ message: 'Settings updated successfully', settings: serverSettings });
});
// Helper function to match dynamic paths
const matchDynamicPath = (pattern, path) => {
// Convert pattern like /users/{id}/posts to regex
const regexPattern = pattern
.replace(/\{[^}]+\}/g, '([^/]+)') // Replace {param} with capture group
.replace(/\//g, '\\/'); // Escape forward slashes
const regex = new RegExp(`^${regexPattern}$`);
const match = path.match(regex);
if (match) {
// Extract parameter names from pattern
const paramNames = pattern.match(/\{([^}]+)\}/g)?.map(p => p.slice(1, -1)) || [];
const paramValues = match.slice(1); // Skip the full match
// Create params object
const params = {};
paramNames.forEach((name, index) => {
params[name] = paramValues[index];
});
return { match: true, params };
}
return { match: false };
};
const parseQueryString = (queryString) => {
// Parse query string into key-value pairs
const params = {};
if (!queryString) return params;
const pairs = queryString.split('&');
for (const pair of pairs) {
const equalIndex = pair.indexOf('=');
if (equalIndex === -1) {
// No = sign, treat as key with empty value
const key = decodeURIComponent(pair);
if (key) {
params[key] = '';
}
} else {
const key = decodeURIComponent(pair.substring(0, equalIndex));
const value = decodeURIComponent(pair.substring(equalIndex + 1));
if (key) {
params[key] = value;
}
}
}
return params;
};
const matchDynamicQuery = (patternQuery, requestQuery) => {
// Match query strings with dynamic variables
// Pattern: start_date={start}&end_date={end}
// Request: start_date=test-value&end_date=test-value2
const patternParams = parseQueryString(patternQuery);
const requestParams = parseQueryString(requestQuery);
// Check if all pattern keys exist in request
for (const [key, patternValue] of Object.entries(patternParams)) {
if (!(key in requestParams)) {
return { match: false };
}
// If pattern value is a dynamic variable {var}, it matches any value
if (patternValue.startsWith('{') && patternValue.endsWith('}')) {
// This is a dynamic variable, it matches any value
continue;
}
// Otherwise, values must match exactly
if (patternValue !== requestParams[key]) {
return { match: false };
}
}
// Check if request has extra params not in pattern (optional - you might want to allow this)
// For now, we'll allow extra params in the request
// Extract dynamic parameter values
const params = {};
for (const [key, patternValue] of Object.entries(patternParams)) {
if (patternValue.startsWith('{') && patternValue.endsWith('}')) {
const paramName = patternValue.slice(1, -1);
params[paramName] = requestParams[key];
}
}
return { match: true, params };
};
// Dynamic mock routing - this should be last to catch all routes
app.use((req, res, next) => {
// Skip static files and management API routes
if (req.path.startsWith('/api/endpoints') ||
req.path.startsWith('/api/settings') ||
req.path.endsWith('.css') ||
req.path.endsWith('.js') ||
req.path.endsWith('.html') ||
req.path.endsWith('.png') ||
req.path.endsWith('.jpg') ||
req.path.endsWith('.jpeg') ||
req.path.endsWith('.gif') ||
req.path.endsWith('.svg') ||
req.path.endsWith('.ico')) {
return next();
}
const endpoints = loadEndpoints();
const method = req.method.toUpperCase();
// Build full request path including query parameters
let requestPath = req.path;
if (req.url.includes('?')) {
// Extract query string from original URL
const queryString = req.url.split('?')[1];
requestPath = `${req.path}?${queryString}`;
}
// Find matching endpoint - first try exact match, then dynamic match
let endpoint = endpoints.find(ep => {
return ep.method === method && ep.path === requestPath;
});
// If no exact match, try dynamic path matching (without query params for path matching)
if (!endpoint) {
const pathWithoutQuery = requestPath.split('?')[0];
const reqQuery = requestPath.includes('?') ? requestPath.split('?')[1] : '';
endpoint = endpoints.find(ep => {
if (ep.method !== method) return false;
const epPathWithoutQuery = ep.path.split('?')[0];
const epQuery = ep.path.includes('?') ? ep.path.split('?')[1] : '';
// Check if path has dynamic segments
const pathHasDynamic = epPathWithoutQuery.includes('{');
// Match path part
let pathMatch = false;
let pathParams = {};
if (pathHasDynamic) {
const matchResult = matchDynamicPath(epPathWithoutQuery, pathWithoutQuery);
if (matchResult.match) {
pathMatch = true;
pathParams = matchResult.params;
}
} else if (epPathWithoutQuery === pathWithoutQuery) {
pathMatch = true;
}
if (!pathMatch) {
return false;
}
// Match query part
if (epQuery && reqQuery) {
// Both have query params - match them
const queryMatch = matchDynamicQuery(epQuery, reqQuery);
if (!queryMatch.match) {
return false;
}
// Merge query params with path params
req.dynamicParams = { ...pathParams, ...queryMatch.params };
} else if (epQuery && !reqQuery) {
// Endpoint expects query params but request doesn't have them
return false;
} else if (!epQuery && reqQuery) {
// Endpoint doesn't have query params but request does - this is OK
req.dynamicParams = pathParams;
} else {
// Neither has query params
req.dynamicParams = pathParams;
}
return true;
});
}
if (!endpoint) {
return next(); // Let Express handle 404 for unmatched routes
}
// Find the selected response or default to first response
let selectedResponse = endpoint.responses.find(r => r.name === endpoint.selectedResponseName);
if (!selectedResponse) {
selectedResponse = endpoint.responses[0];
}
// Set cache control headers to prevent browser caching
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
// Apply response delay if configured
if (serverSettings.responseDelay > 0) {
setTimeout(() => {
res.status(selectedResponse.statusCode).json(selectedResponse.body);
}, serverSettings.responseDelay);
} else {
res.status(selectedResponse.statusCode).json(selectedResponse.body);
}
});
// Serve the GUI
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Check port availability and start server
const startServer = async () => {
const portAvailable = await isPortAvailable(PORT);
if (!portAvailable) {
console.log(`⚠️ Warning: Port ${PORT} is already in use!`);
console.log(` Another process might be using this port.`);
console.log(` Try using a different port with: --port <number>`);
console.log(` Or check what's running on port ${PORT} with: lsof -i :${PORT}`);
console.log('');
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`🚀 Mocker Server running on http://0.0.0.0:${PORT}`);
console.log(`📱 GUI available at http://0.0.0.0:${PORT}`);
console.log(`📁 Mocks directory: ${MOCKS_DIR}`);
console.log(`💡 Use --help for more options`);
});
};
startServer().catch(error => {
console.error('❌ Failed to start server:', error.message);
process.exit(1);
});