-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1150 lines (1033 loc) · 41.3 KB
/
server.ts
File metadata and controls
1150 lines (1033 loc) · 41.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =============================================================================
// MINI API GATEWAY SERVER
// =============================================================================
// A lightweight API Gateway with proxy, authentication, and rate limiting
// Features:
// - JWT/Bearer token authentication middleware
// - IP-based rate limiting (configurable requests per minute)
// - Request/Response transformation (field injection)
// - Real-time monitoring dashboard with Tailwind CSS
// - Request history and statistics tracking
//
// Technology Stack:
// - Runtime: Node.js (via @elysiajs/node adapter)
// - Framework: Elysia.js
// - Frontend: Tailwind CSS (CDN)
// - Target API: JSONPlaceholder (demo REST API)
// =============================================================================
import { Elysia } from 'elysia'
import { node } from '@elysiajs/node'
import { html } from '@elysiajs/html'
// =============================================================================
// CONFIGURATION
// =============================================================================
/**
* Server port configuration
* Can be overridden via PORT environment variable
*/
const PORT = Number(process.env.PORT) || 8080
/**
* Rate limit threshold
* Maximum number of requests allowed per IP per minute
*/
const RATE_LIMIT = 20
/**
* Target API base URL
* All /proxy/* requests will be forwarded to this endpoint
*/
const TARGET_API = 'https://jsonplaceholder.typicode.com'
/**
* Authentication token for protected routes
* In production, use proper JWT validation with secrets from env
*/
const AUTH_TOKEN = 'Bearer secret-token'
// =============================================================================
// IN-MEMORY DATA STORES
// =============================================================================
// Note: In production, use Redis for distributed rate limiting and persistence
/**
* IP-based rate limiting store
* Tracks request count and window start time per IP address
*/
interface RateLimitRecord {
count: number
ts: number
}
const ipMap = new Map<string, RateLimitRecord>()
/**
* Request history for monitoring dashboard
* Stores last N requests with metadata
*/
interface RequestLogEntry {
id: number
method: string
path: string
status: number
duration: number
timestamp: number
ip: string
}
const requestHistory: RequestLogEntry[] = []
let requestIdCounter = 0
/**
* Gateway statistics
* Aggregated metrics for monitoring
*/
interface GatewayStats {
totalRequests: number
successCount: number
errorCount: number
rateLimitedCount: number
avgResponseTime: number
startTime: number
}
const stats: GatewayStats = {
totalRequests: 0,
successCount: 0,
errorCount: 0,
rateLimitedCount: 0,
avgResponseTime: 0,
startTime: Date.now()
}
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
/**
* Extracts client IP address from request headers
* Handles X-Forwarded-For header for proxied requests
*
* @param request - Incoming request object
* @returns Client IP address string
*/
const getClientIp = (request: Request): string => {
const forwarded = request.headers.get('x-forwarded-for')
return forwarded?.split(',')[0]?.trim() || 'localhost'
}
/**
* Checks rate limit for given IP address
* Implements sliding window rate limiting
*
* @param ip - Client IP address
* @returns Object with allowed status and remaining requests
*/
const checkRateLimit = (ip: string): { allowed: boolean; remaining: number; resetIn: number } => {
const now = Date.now()
const record = ipMap.get(ip) || { count: 0, ts: now }
// Reset window if 60 seconds have passed
if (now - record.ts > 60_000) {
record.count = 0
record.ts = now
}
const remaining = Math.max(0, RATE_LIMIT - record.count)
const resetIn = Math.max(0, 60 - Math.floor((now - record.ts) / 1000))
return {
allowed: record.count < RATE_LIMIT,
remaining,
resetIn
}
}
/**
* Logs a request to history and updates statistics
*
* @param entry - Request log entry to record
*/
const logRequest = (entry: Omit<RequestLogEntry, 'id'>): void => {
// Add to history with unique ID
requestHistory.unshift({ ...entry, id: ++requestIdCounter })
// Keep only last 50 entries
if (requestHistory.length > 50) {
requestHistory.pop()
}
// Update statistics
stats.totalRequests++
if (entry.status >= 200 && entry.status < 400) {
stats.successCount++
} else if (entry.status === 429) {
stats.rateLimitedCount++
} else {
stats.errorCount++
}
// Update average response time (rolling average)
stats.avgResponseTime = Math.round(
(stats.avgResponseTime * (stats.totalRequests - 1) + entry.duration) / stats.totalRequests
)
}
// =============================================================================
// UI HTML TEMPLATE
// =============================================================================
/**
* Dashboard UI HTML
* Modern dark-themed interface with Tailwind CSS
* Features: preset buttons, live stats, request history, cURL generator
*/
const dashboardHTML = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Gateway Dashboard</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Tailwind Configuration -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
dark: {
800: '#1e293b',
900: '#0f172a',
950: '#020617'
}
}
}
}
}
</script>
<!-- Custom Styles -->
<style>
.gradient-bg {
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 50%, #0f172a 100%);
}
.glass {
background: rgba(255, 255, 255, 0.03);
backdrop-filter: blur(10px);
}
.method-GET { background: rgba(34, 197, 94, 0.2); color: #22c55e; }
.method-POST { background: rgba(59, 130, 246, 0.2); color: #3b82f6; }
.method-PUT { background: rgba(234, 179, 8, 0.2); color: #eab308; }
.method-PATCH { background: rgba(168, 85, 247, 0.2); color: #a855f7; }
.method-DELETE { background: rgba(239, 68, 68, 0.2); color: #ef4444; }
.scrollbar-thin::-webkit-scrollbar { width: 6px; }
.scrollbar-thin::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); border-radius: 3px; }
.scrollbar-thin::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.2); border-radius: 3px; }
</style>
</head>
<body class="gradient-bg min-h-screen text-slate-200">
<!-- ===================================================================== -->
<!-- HEADER -->
<!-- ===================================================================== -->
<header class="border-b border-slate-800">
<div class="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<span class="text-3xl">📡</span>
<div>
<h1 class="text-xl font-bold text-white">API Gateway</h1>
<p class="text-sm text-slate-500">Proxy & Rate Limiter</p>
</div>
</div>
<div class="flex items-center gap-4">
<!-- Rate Limit Indicator -->
<div id="rateLimitIndicator" class="flex items-center gap-2 px-3 py-1.5 bg-slate-800 rounded-full text-sm">
<span class="text-slate-400">Rate Limit:</span>
<span id="rateLimitCount" class="text-emerald-400 font-mono">${RATE_LIMIT}/${RATE_LIMIT}</span>
</div>
<!-- Status Badge -->
<span class="flex items-center gap-2 px-3 py-1.5 bg-emerald-500/10 text-emerald-400 rounded-full text-sm">
<span class="w-2 h-2 bg-emerald-400 rounded-full animate-pulse"></span>
Online
</span>
</div>
</div>
</header>
<!-- ===================================================================== -->
<!-- MAIN CONTENT -->
<!-- ===================================================================== -->
<main class="max-w-7xl mx-auto px-6 py-8">
<!-- Target API Info Banner -->
<div class="mb-6 p-4 rounded-xl bg-indigo-500/10 border border-indigo-500/20">
<div class="flex flex-wrap items-center gap-4 text-sm">
<div class="flex items-center gap-2">
<span class="text-slate-400">Target API:</span>
<code class="text-indigo-300">${TARGET_API}</code>
</div>
<div class="text-slate-600">|</div>
<div class="flex items-center gap-2">
<span class="text-slate-400">Proxy Endpoint:</span>
<code class="text-indigo-300">/proxy/*</code>
</div>
<div class="text-slate-600">|</div>
<div class="flex items-center gap-2">
<span class="text-slate-400">Auth:</span>
<code class="text-indigo-300">Bearer secret-token</code>
</div>
</div>
</div>
<div class="grid lg:grid-cols-3 gap-6">
<!-- ================================================================= -->
<!-- LEFT COLUMN: REQUEST BUILDER -->
<!-- ================================================================= -->
<div class="lg:col-span-2 space-y-6">
<!-- Request Builder Card -->
<div class="glass rounded-2xl border border-slate-800 p-6">
<h2 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<span>🚀</span> Send Request
</h2>
<!-- Quick Presets -->
<div class="mb-5">
<label class="block text-sm text-slate-500 mb-3">Quick Presets</label>
<div class="grid grid-cols-2 md:grid-cols-4 gap-2">
<button onclick="loadPreset('getPosts')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-GET px-1.5 py-0.5 rounded text-xs font-bold mr-1">GET</span>
/posts
</button>
<button onclick="loadPreset('getPost')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-GET px-1.5 py-0.5 rounded text-xs font-bold mr-1">GET</span>
/posts/1
</button>
<button onclick="loadPreset('getUsers')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-GET px-1.5 py-0.5 rounded text-xs font-bold mr-1">GET</span>
/users
</button>
<button onclick="loadPreset('getComments')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-GET px-1.5 py-0.5 rounded text-xs font-bold mr-1">GET</span>
/posts/1/comments
</button>
<button onclick="loadPreset('createPost')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-POST px-1.5 py-0.5 rounded text-xs font-bold mr-1">POST</span>
/posts
</button>
<button onclick="loadPreset('updatePost')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-PUT px-1.5 py-0.5 rounded text-xs font-bold mr-1">PUT</span>
/posts/1
</button>
<button onclick="loadPreset('patchPost')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-PATCH px-1.5 py-0.5 rounded text-xs font-bold mr-1">PATCH</span>
/posts/1
</button>
<button onclick="loadPreset('deletePost')"
class="preset-btn px-3 py-2 text-sm bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all hover:scale-[1.02] text-left">
<span class="method-DELETE px-1.5 py-0.5 rounded text-xs font-bold mr-1">DEL</span>
/posts/1
</button>
</div>
</div>
<!-- Method & Path Selection -->
<div class="grid md:grid-cols-4 gap-4 mb-4">
<div>
<label class="block text-sm text-slate-500 mb-2">Method</label>
<select id="method" onchange="updateCurlExample()"
class="w-full px-4 py-2.5 bg-slate-900/50 border border-slate-700 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="PATCH">PATCH</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div class="md:col-span-3">
<label class="block text-sm text-slate-500 mb-2">Path</label>
<div class="flex">
<span class="px-4 py-2.5 bg-slate-800 border border-r-0 border-slate-700 rounded-l-xl text-slate-500 text-sm">/proxy/</span>
<input type="text" id="path" value="posts" oninput="updateCurlExample()"
class="flex-1 px-4 py-2.5 bg-slate-900/50 border border-slate-700 rounded-r-xl text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all font-mono">
</div>
</div>
</div>
<!-- Request Body -->
<div class="mb-4" id="bodySection">
<label class="block text-sm text-slate-500 mb-2">Request Body (JSON)</label>
<textarea id="body" rows="4" oninput="updateCurlExample()"
class="w-full px-4 py-3 bg-slate-900/50 border border-slate-700 rounded-xl text-white font-mono text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all resize-none scrollbar-thin"
placeholder="Optional JSON body for POST/PUT/PATCH requests"></textarea>
</div>
<!-- Action Buttons -->
<div class="flex gap-3">
<button onclick="sendRequest()" id="sendBtn"
class="flex-1 py-3 bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white font-semibold rounded-xl transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg shadow-indigo-500/25 flex items-center justify-center gap-2">
<span id="sendBtnText">Send Request</span>
<span id="sendBtnSpinner" class="hidden">
<svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
</svg>
</span>
</button>
<button onclick="clearAll()"
class="px-6 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl transition-colors">
Clear
</button>
</div>
</div>
<!-- Response Panel -->
<div id="responsePanel" class="glass rounded-2xl border border-slate-800 p-6 hidden">
<div class="flex items-center justify-between mb-4">
<h2 class="text-lg font-semibold text-white flex items-center gap-2">
<span>📥</span> Response
</h2>
<div class="flex items-center gap-3">
<span id="responseDuration" class="text-sm text-slate-500"></span>
<span id="statusBadge" class="px-3 py-1 rounded-full text-sm font-medium"></span>
</div>
</div>
<pre id="responseBody" class="p-4 bg-slate-900/70 rounded-xl text-sm font-mono overflow-auto max-h-96 text-slate-300 scrollbar-thin"></pre>
</div>
</div>
<!-- ================================================================= -->
<!-- RIGHT COLUMN: STATS & TOOLS -->
<!-- ================================================================= -->
<div class="space-y-6">
<!-- Statistics Card -->
<div class="glass rounded-2xl border border-slate-800 p-6">
<h2 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<span>📊</span> Statistics
</h2>
<div class="grid grid-cols-2 gap-3">
<div class="p-3 bg-slate-900/50 rounded-xl text-center">
<div id="statTotal" class="text-2xl font-bold text-indigo-400">0</div>
<div class="text-xs text-slate-500">Total</div>
</div>
<div class="p-3 bg-slate-900/50 rounded-xl text-center">
<div id="statSuccess" class="text-2xl font-bold text-emerald-400">0</div>
<div class="text-xs text-slate-500">Success</div>
</div>
<div class="p-3 bg-slate-900/50 rounded-xl text-center">
<div id="statErrors" class="text-2xl font-bold text-red-400">0</div>
<div class="text-xs text-slate-500">Errors</div>
</div>
<div class="p-3 bg-slate-900/50 rounded-xl text-center">
<div id="statAvgTime" class="text-2xl font-bold text-amber-400">0</div>
<div class="text-xs text-slate-500">Avg ms</div>
</div>
</div>
<button onclick="refreshStats()"
class="w-full mt-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg text-sm transition-colors">
↻ Refresh Stats
</button>
</div>
<!-- Request History -->
<div class="glass rounded-2xl border border-slate-800 p-6">
<h2 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<span>📋</span> Recent Requests
</h2>
<div id="historyList" class="space-y-2 max-h-48 overflow-y-auto scrollbar-thin">
<div class="text-slate-500 text-sm text-center py-4">No requests yet</div>
</div>
</div>
<!-- cURL Example -->
<div class="glass rounded-2xl border border-slate-800 p-6">
<h2 class="text-lg font-semibold text-white mb-3 flex items-center gap-2">
<span>💻</span> cURL
<span class="text-xs text-slate-500 font-normal ml-auto">Live Preview</span>
</h2>
<div class="relative">
<pre id="curlExample" class="p-3 bg-slate-900/70 rounded-xl text-xs font-mono text-slate-400 overflow-x-auto whitespace-pre-wrap break-all max-h-40 scrollbar-thin"></pre>
<button onclick="copyCurl()" id="copyBtn"
class="absolute top-2 right-2 p-1.5 bg-slate-800 hover:bg-slate-700 rounded-lg text-slate-400 hover:text-white transition-colors text-sm">
📋
</button>
</div>
</div>
<!-- Gateway Info -->
<div class="glass rounded-2xl border border-slate-800 p-6">
<h2 class="text-lg font-semibold text-white mb-3 flex items-center gap-2">
<span>⚙️</span> Gateway Config
</h2>
<div class="space-y-2 text-sm">
<div class="flex justify-between">
<span class="text-slate-500">Rate Limit</span>
<span class="text-slate-300">${RATE_LIMIT} req/min</span>
</div>
<div class="flex justify-between">
<span class="text-slate-500">Target API</span>
<span class="text-slate-300 truncate ml-2">jsonplaceholder</span>
</div>
<div class="flex justify-between">
<span class="text-slate-500">Field Injection</span>
<span class="text-emerald-400">Enabled</span>
</div>
<div class="flex justify-between">
<span class="text-slate-500">Auth Required</span>
<span class="text-emerald-400">Yes</span>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- ===================================================================== -->
<!-- FOOTER -->
<!-- ===================================================================== -->
<footer class="border-t border-slate-800 mt-12">
<div class="max-w-7xl mx-auto px-6 py-4 text-center text-sm text-slate-600">
API Gateway • Built with Elysia + Node.js
</div>
</footer>
<!-- ===================================================================== -->
<!-- JAVASCRIPT -->
<!-- ===================================================================== -->
<script>
// =========================================================================
// PRESET CONFIGURATIONS
// =========================================================================
const presets = {
// GET requests
getPosts: {
method: 'GET',
path: 'posts',
body: null,
description: 'Get all posts'
},
getPost: {
method: 'GET',
path: 'posts/1',
body: null,
description: 'Get single post'
},
getUsers: {
method: 'GET',
path: 'users',
body: null,
description: 'Get all users'
},
getComments: {
method: 'GET',
path: 'posts/1/comments', // ✅ Fixed: proper nested resource path
body: null,
description: 'Get comments for post 1'
},
// POST request
createPost: {
method: 'POST',
path: 'posts',
body: {
title: 'Hello World',
body: 'This is a test post created via API Gateway',
userId: 1
},
description: 'Create new post'
},
// PUT request (full update)
updatePost: {
method: 'PUT',
path: 'posts/1',
body: {
id: 1,
title: 'Updated Title',
body: 'This post has been fully updated',
userId: 1
},
description: 'Update entire post'
},
// PATCH request (partial update)
patchPost: {
method: 'PATCH',
path: 'posts/1',
body: {
title: 'Patched Title Only'
},
description: 'Partial post update'
},
// DELETE request
deletePost: {
method: 'DELETE',
path: 'posts/1',
body: null,
description: 'Delete post'
}
};
// =========================================================================
// UI FUNCTIONS
// =========================================================================
/**
* Loads a preset configuration into the form
*/
function loadPreset(name) {
const preset = presets[name];
document.getElementById('method').value = preset.method;
document.getElementById('path').value = preset.path;
document.getElementById('body').value = preset.body ? JSON.stringify(preset.body, null, 2) : '';
updateBodyVisibility();
updateCurlExample();
}
/**
* Shows/hides body textarea based on HTTP method
*/
function updateBodyVisibility() {
const method = document.getElementById('method').value;
const bodySection = document.getElementById('bodySection');
const hasBody = ['POST', 'PUT', 'PATCH'].includes(method);
bodySection.style.display = hasBody ? 'block' : 'none';
}
/**
* Updates the cURL example based on current form values
*/
function updateCurlExample() {
const method = document.getElementById('method').value;
const path = document.getElementById('path').value;
const bodyText = document.getElementById('body').value.trim();
// Methods that support request body
const bodyMethods = ['POST', 'PUT', 'PATCH'];
const hasBody = bodyMethods.includes(method);
// Use origin for universal URL (works on localhost, render.com, etc.)
const baseUrl = window.location.origin;
// Start building cURL command
let curl = \`curl -X \${method} \${baseUrl}/proxy/\${path}\`;
// Only add Content-Type for methods with body
if (hasBody) {
curl += \` \\
-H "Content-Type: application/json"\`;
}
// Always add Authorization
curl += \` \\
-H "Authorization: Bearer secret-token"\`;
// Add body only for POST/PUT/PATCH with valid JSON
if (hasBody && bodyText) {
try {
const body = JSON.parse(bodyText);
curl += \` \\
-d '\${JSON.stringify(body)}'\`;
} catch {
// Invalid JSON - don't add body
}
}
document.getElementById('curlExample').textContent = curl;
}
/**
* Sends the request to the API gateway
*/
async function sendRequest() {
const method = document.getElementById('method').value;
const path = document.getElementById('path').value.trim();
const bodyText = document.getElementById('body').value.trim();
// Show loading state
document.getElementById('sendBtnText').textContent = 'Sending...';
document.getElementById('sendBtnSpinner').classList.remove('hidden');
document.getElementById('sendBtn').disabled = true;
// Methods that support request body
const bodyMethods = ['POST', 'PUT', 'PATCH'];
const hasBody = bodyMethods.includes(method);
let body = null;
if (hasBody && bodyText) {
try {
body = JSON.parse(bodyText);
} catch (e) {
showResponse(400, { error: 'Invalid JSON in request body' }, 0, false);
resetSendButton();
return;
}
}
const startTime = performance.now();
// Build headers - only add Content-Type if we have a body
const headers = {
'Authorization': 'Bearer secret-token'
};
if (hasBody && body) {
headers['Content-Type'] = 'application/json';
}
try {
const res = await fetch('/proxy/' + path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
});
const duration = Math.round(performance.now() - startTime);
const data = await res.json();
showResponse(res.status, data, duration, res.ok);
// Refresh stats and history
setTimeout(() => {
refreshStats();
refreshHistory();
updateRateLimitDisplay();
}, 300);
} catch (err) {
showResponse(500, { error: err.message }, 0, false);
}
resetSendButton();
}
/**
* Resets the send button state
*/
function resetSendButton() {
document.getElementById('sendBtnText').textContent = 'Send Request';
document.getElementById('sendBtnSpinner').classList.add('hidden');
document.getElementById('sendBtn').disabled = false;
}
/**
* Displays the API response
*/
function showResponse(status, data, duration, success) {
document.getElementById('responsePanel').classList.remove('hidden');
const badge = document.getElementById('statusBadge');
badge.textContent = status;
badge.className = 'px-3 py-1 rounded-full text-sm font-medium ' +
(success ? 'bg-emerald-500/20 text-emerald-400' : 'bg-red-500/20 text-red-400');
document.getElementById('responseDuration').textContent = duration + 'ms';
document.getElementById('responseBody').textContent = JSON.stringify(data, null, 2);
}
/**
* Clears the form and response
*/
function clearAll() {
document.getElementById('responsePanel').classList.add('hidden');
document.getElementById('path').value = 'posts';
document.getElementById('method').value = 'GET';
document.getElementById('body').value = '';
updateBodyVisibility();
updateCurlExample();
}
/**
* Copies cURL to clipboard
*/
function copyCurl() {
const curl = document.getElementById('curlExample').textContent;
navigator.clipboard.writeText(curl).then(() => {
const btn = document.getElementById('copyBtn');
btn.textContent = '✓';
setTimeout(() => btn.textContent = '📋', 1500);
});
}
// =========================================================================
// DATA FETCHING
// =========================================================================
async function refreshStats() {
try {
const res = await fetch('/api/stats');
const data = await res.json();
document.getElementById('statTotal').textContent = data.totalRequests;
document.getElementById('statSuccess').textContent = data.successCount;
document.getElementById('statErrors').textContent = data.errorCount;
document.getElementById('statAvgTime').textContent = data.avgResponseTime;
} catch {}
}
async function refreshHistory() {
try {
const res = await fetch('/api/history');
const data = await res.json();
const list = document.getElementById('historyList');
if (data.length === 0) {
list.innerHTML = '<div class="text-slate-500 text-sm text-center py-4">No requests yet</div>';
return;
}
list.innerHTML = data.slice(0, 10).map(req => \`
<div class="flex items-center justify-between p-2 bg-slate-900/50 rounded-lg text-sm">
<div class="flex items-center gap-2">
<span class="method-\${req.method} px-1.5 py-0.5 rounded text-xs font-bold">\${req.method}</span>
<span class="text-slate-400 truncate max-w-[100px]">/\${req.path}</span>
</div>
<div class="flex items-center gap-2">
<span class="text-slate-500">\${req.duration}ms</span>
<span class="\${req.status < 400 ? 'text-emerald-400' : 'text-red-400'}">\${req.status}</span>
</div>
</div>
\`).join('');
} catch {}
}
async function updateRateLimitDisplay() {
try {
const res = await fetch('/api/rate-limit');
const data = await res.json();
document.getElementById('rateLimitCount').textContent = \`\${data.remaining}/\${data.limit}\`;
document.getElementById('rateLimitCount').className =
data.remaining < 5 ? 'text-red-400 font-mono' : 'text-emerald-400 font-mono';
} catch {}
}
// =========================================================================
// INITIALIZATION
// =========================================================================
// Set up event listeners
document.getElementById('method').addEventListener('change', () => {
updateBodyVisibility();
updateCurlExample();
});
// Initial state
updateBodyVisibility();
updateCurlExample();
refreshStats();
refreshHistory();
updateRateLimitDisplay();
// Auto-refresh every 5 seconds
setInterval(() => {
refreshStats();
refreshHistory();
updateRateLimitDisplay();
}, 5000);
</script>
</body>
</html>
`
// =============================================================================
// APPLICATION SETUP
// =============================================================================
const app = new Elysia({ adapter: node() })
.use(html())
// ===========================================================================
// PUBLIC ROUTES (No Authentication)
// ===========================================================================
/**
* GET /
* Dashboard UI - serves the monitoring and testing interface
*/
.get('/', () => dashboardHTML)
/**
* GET /api/stats
* Returns gateway statistics for the dashboard
*/
.get('/api/stats', () => ({
totalRequests: stats.totalRequests,
successCount: stats.successCount,
errorCount: stats.errorCount,
rateLimitedCount: stats.rateLimitedCount,
avgResponseTime: stats.avgResponseTime,
uptime: Math.floor((Date.now() - stats.startTime) / 1000)
}))
/**
* GET /api/history
* Returns recent request history for the dashboard
*/
.get('/api/history', () => requestHistory.slice(0, 20))
/**
* GET /api/rate-limit
* Returns current rate limit status for the requesting IP
*/
.get('/api/rate-limit', ({ request }) => {
const ip = getClientIp(request)
const status = checkRateLimit(ip)
return {
limit: RATE_LIMIT,
remaining: status.remaining,
resetIn: status.resetIn
}
})
/**
* GET /health
* Health check endpoint for load balancers and monitoring
*/
.get('/health', () => ({
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString()
}))
// ===========================================================================
// PROTECTED PROXY ROUTES
// ===========================================================================
.group('/proxy', (app) =>
app
// -----------------------------------------------------------------------
// Authentication Middleware
// -----------------------------------------------------------------------
// Validates Bearer token in Authorization header
// Returns 401 Unauthorized if token is missing or invalid
.onBeforeHandle(({ headers, set, request }) => {
const token = headers['authorization']
if (!token || token !== AUTH_TOKEN) {
// Log failed auth attempt
logRequest({
method: request.method,
path: 'auth-failed',
status: 401,
duration: 0,
timestamp: Date.now(),
ip: getClientIp(request)
})
set.status = 401
return { error: 'Unauthorized', message: 'Valid Bearer token required' }
}
})
// -----------------------------------------------------------------------
// Rate Limiting Middleware
// -----------------------------------------------------------------------
// Implements sliding window rate limiting per IP address
// Returns 429 Too Many Requests when limit exceeded
.onBeforeHandle(({ request, set }) => {
const ip = getClientIp(request)
const now = Date.now()
const record = ipMap.get(ip) || { count: 0, ts: now }
// Reset counter if window has passed (60 seconds)
if (now - record.ts > 60_000) {
record.count = 0
record.ts = now
}
// Increment request count
record.count++
ipMap.set(ip, record)
// Check if rate limit exceeded
if (record.count > RATE_LIMIT) {
logRequest({
method: request.method,
path: 'rate-limited',
status: 429,
duration: 0,
timestamp: Date.now(),
ip
})
set.status = 429
set.headers = {
'X-RateLimit-Limit': String(RATE_LIMIT),
'X-RateLimit-Remaining': '0',
'X-RateLimit-Reset': String(Math.ceil((record.ts + 60_000) / 1000))
}
return {
error: 'Rate limit exceeded',
message: `Maximum ${RATE_LIMIT} requests per minute`,
retryAfter: Math.ceil((record.ts + 60_000 - now) / 1000)
}
}
})
// -----------------------------------------------------------------------
// Proxy Handler
// -----------------------------------------------------------------------
// Forwards all HTTP methods to target API
// Safely handles any response type
.all('/*', async ({ params, request, body, set }) => {
const startTime = Date.now()
const path = params['*']
const url = `${TARGET_API}/${path}`
const method = request.method
const ip = getClientIp(request)
// Methods that should NOT have a body or Content-Type header
const noBodyMethods = ['GET', 'HEAD', 'OPTIONS', 'DELETE']
const hasBody = !noBodyMethods.includes(method)
// Prepare fetch options
const fetchOptions: RequestInit = {
method,
headers: {
'User-Agent': 'API-Gateway/1.0'
}
}
// Only add Content-Type and body for methods that support it
if (hasBody && body) {