-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAPIExplorer.tsx
838 lines (785 loc) · 28.8 KB
/
APIExplorer.tsx
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
import { useCallback, useEffect, useMemo, useState } from 'react'
import type {
APIRequest,
APIResponse,
Endpoint,
LocalStorageHistoryItem,
} from '../../types'
import {
Badge,
Spinner,
Tabs,
FieldRows,
type FieldRow,
Loading,
} from '../shared'
import {
flattenPaths,
generatePath,
generatePathParams,
formatResponseTime,
formatFileSize,
fieldRowArrToHeaders,
getHost,
generateResponse,
isValidUrl,
} from '../../lib/utils'
import APIResponseContent from './APIResponseContent'
import CodeEditor from './CodeEditor'
import APIMenu from './APIMenu'
import APIHistory from './APIHistory'
import FileUpload from '../storage/FileUpload'
import { useWebSocket } from '../../lib/hooks/use-web-socket'
import { useHistory } from '../../lib/hooks/use-history'
import AppLayout from '../layout/AppLayout'
import APITreeView from './APITreeView'
import { copyToClipboard } from '../../lib/utils/copy-to-clipboard'
import toast from 'react-hot-toast'
import {
ClipboardIcon,
InformationCircleIcon,
} from '@heroicons/react/24/outline'
import { APIMethodBadge } from './APIMethodBadge'
import { Button } from '../ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'
import BreadCrumbs from '../layout/BreadCrumbs'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from '../ui/select'
import { Alert } from '../ui/alert'
import SectionCard from '../shared/SectionCard'
import NotFoundAlert from '../shared/NotFoundAlert'
const getTabCount = (rows: FieldRow[]) => {
if (!rows) return 0
return rows.filter((r) => !!r.key).length
}
export const LOCAL_STORAGE_KEY = 'nitric-local-dash-api-history'
const requestDefault = {
pathParams: [],
queryParams: [
{
key: '',
value: '',
},
],
headers: [
{
key: 'Accept',
value: '*/*',
},
{
key: 'User-Agent',
value: 'Nitric Client (https://www.nitric.io)',
},
{
key: 'Content-Type',
value: 'application/json',
},
],
}
const reqBodyTypes = [
{ name: 'JSON', contentType: 'application/json' },
{ name: 'Text', contentType: 'text/plain' },
{ name: 'Binary', contentType: 'application/octet-stream' },
]
const APIExplorer = () => {
const { data, loading } = useWebSocket()
const [callLoading, setCallLoading] = useState(false)
const { data: history } = useHistory('apis')
const [JSONBody, setJSONBody] = useState<string>('')
const [fileToUpload, setFileToUpload] = useState<File>()
const [textBody, setTextBody] = useState<string>('')
const [request, setRequest] = useState<APIRequest>(requestDefault)
const [response, setResponse] = useState<APIResponse>()
const [selectedApiEndpoint, setSelectedApiEndpoint] = useState<Endpoint>()
const [currentTabIndex, setCurrentTabIndex] = useState(0)
const [bodyTabIndex, setBodyTabIndex] = useState(0)
const [responseTabIndex, setResponseTabIndex] = useState(0)
const [requiredPathParamErrors, setRequiredPathParamErrors] = useState({})
const paths = useMemo(
() =>
data?.apis
?.filter((api) => api.spec)
.map((api) => flattenPaths(api.spec))
.flat(),
[data],
)
const selectedDoesNotExist = useMemo(
() =>
!selectedApiEndpoint ||
!paths?.find((p) => p.id === selectedApiEndpoint.id),
[selectedApiEndpoint, data],
)
// Load single history from localStorage on mount
useEffect(() => {
if (selectedApiEndpoint) {
const storedHistory = localStorage.getItem(
`${LOCAL_STORAGE_KEY}-${selectedApiEndpoint.id}`,
)
if (storedHistory) {
const history: LocalStorageHistoryItem = JSON.parse(storedHistory)
setJSONBody(history.JSONBody)
setRequest((prev) => ({
...prev,
...history.request,
pathParams: generatePathParams(selectedApiEndpoint, history.request),
}))
} else {
// clear
setJSONBody('')
setRequest((prev) => ({
...prev,
...requestDefault,
pathParams: generatePathParams(selectedApiEndpoint, requestDefault),
}))
}
// set history
localStorage.setItem(
`${LOCAL_STORAGE_KEY}-last-path-id`,
selectedApiEndpoint.id,
)
// clear response
setResponse(undefined)
}
}, [selectedApiEndpoint])
// Load request history
useEffect(() => {
const localHistory = localStorage.getItem(`${LOCAL_STORAGE_KEY}-requests`)
if (!localHistory) {
localStorage.setItem(`${LOCAL_STORAGE_KEY}-requests`, JSON.stringify([]))
return
}
}, [])
useEffect(() => {
if (paths?.length) {
// restore history or select first if not selected
if (!selectedApiEndpoint) {
const previousId = localStorage.getItem(
`${LOCAL_STORAGE_KEY}-last-path-id`,
)
const path =
(previousId && paths.find((p) => p.id === previousId)) || paths[0]
setSelectedApiEndpoint(path)
setRequest((prev) => ({
...prev,
method: path.method,
}))
} else {
// could be a refresh from ws, so update the selected endpoint
const latest = paths.find((p) => p.id === selectedApiEndpoint.id)
if (latest) {
setSelectedApiEndpoint(latest)
setRequest((prev) => ({
...prev,
method: latest.method,
}))
}
}
}
}, [paths])
useEffect(() => {
if (selectedApiEndpoint) {
const generatedPath = generatePath(
selectedApiEndpoint.path,
request.pathParams,
request.queryParams,
)
setRequest((prev) => ({
...prev,
path: generatedPath,
method: selectedApiEndpoint.method,
}))
}
}, [selectedApiEndpoint, request.pathParams, request.queryParams])
// Save state to local storage whenever it changes
useEffect(() => {
if (selectedApiEndpoint) {
localStorage.setItem(
`${LOCAL_STORAGE_KEY}-${selectedApiEndpoint.id}`,
JSON.stringify({
request,
JSONBody,
}),
)
}
}, [request, JSONBody])
const onDrop = useCallback(
async (acceptedFiles: File[]) => setFileToUpload(acceptedFiles[0]),
[],
)
const apiAddress =
selectedApiEndpoint && data?.apiAddresses
? data.apiAddresses[selectedApiEndpoint.api]
: null
const tabs = [
{
name: 'Params',
count: getTabCount(request.queryParams) + getTabCount(request.pathParams),
},
{ name: 'Headers', count: getTabCount(request.headers) },
{ name: 'Body', count: JSONBody ? 1 : undefined },
]
const currentTabName = tabs[currentTabIndex].name
const currentBodyTab = reqBodyTypes[bodyTabIndex]
const refreshPathParamErrors = () => {
const newPathParamErrors: Record<number, FieldRow> = {}
const emptyParams = request.pathParams.filter((p, idx) => {
if (p.value === '') {
newPathParamErrors[idx] = p
return true
}
return false
})
setRequiredPathParamErrors(newPathParamErrors)
return emptyParams
}
useEffect(() => {
if (Object.keys(requiredPathParamErrors).length) {
refreshPathParamErrors()
}
}, [request.pathParams])
const handleSend = async (
e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
) => {
if (!selectedApiEndpoint) return
setCallLoading(true)
e.preventDefault()
if (request.pathParams.length) {
const emptyParams = refreshPathParamErrors()
if (emptyParams.length) {
setCallLoading(false)
toast.error(
`Required path parameter(s) missing: ${emptyParams
.map((p) => p.key)
.join(', ')}`,
)
return
}
const invalidValues = request.pathParams.filter(
(param) => !isValidUrl(param.value),
)
if (invalidValues.length) {
setCallLoading(false)
toast.error(
`Invalid path parameter value for: ${invalidValues
.map((p) => p.key)
.join(', ')}`,
)
return
}
}
const { path, method, headers } = request
const url = `http://${getHost()}/api/call` + path
// Set a default content type if not set
const shouldAddContentType = !headers.find(
({ key }) => key.toLowerCase() === 'content-type',
)
const requestOptions: RequestInit = {
method,
headers: fieldRowArrToHeaders([
...(shouldAddContentType
? [
...headers,
{ key: 'Content-Type', value: currentBodyTab.contentType },
]
: headers),
{
key: 'X-Nitric-Local-Call-Address',
value: apiAddress || 'localhost:4001',
},
]),
}
if (method !== 'GET' && method !== 'HEAD') {
// handle body in request
if (currentBodyTab.name === 'Binary' && fileToUpload) {
requestOptions.body = fileToUpload
} else if (currentBodyTab.name === 'JSON' && JSONBody.trim()) {
requestOptions.body = JSONBody
} else if (currentBodyTab.name === 'Text' && textBody) {
requestOptions.body = textBody
}
}
const startTime = window.performance.now()
const res = await fetch(url, requestOptions)
const callResponse = await generateResponse(res, startTime)
setResponse(callResponse)
setTimeout(() => setCallLoading(false), 300)
}
return (
<AppLayout
title="APIs"
hideTitle
routePath={'/'}
secondLevelNav={
paths?.length && selectedApiEndpoint && request?.method ? (
<>
<div className="flex min-h-12 items-center justify-between px-2 py-1">
<span className="text-lg">APIs</span>
<APIMenu
selected={selectedApiEndpoint}
onAfterClear={() => {
setJSONBody('')
setRequest({
...requestDefault,
method: selectedApiEndpoint.method,
path: generatePath(selectedApiEndpoint.path, [], []),
pathParams: generatePathParams(
selectedApiEndpoint,
requestDefault,
),
})
}}
/>
</div>
<APITreeView
defaultTreeIndex={selectedApiEndpoint.id}
onSelect={(endpoint) => {
setSelectedApiEndpoint(endpoint)
}}
endpoints={paths}
/>
</>
) : null
}
>
<Loading delay={400} conditionToShow={!loading}>
{paths?.length && selectedApiEndpoint && request?.method ? (
<div className="flex max-w-7xl flex-col gap-8 md:pr-8">
<div className="flex w-full flex-col gap-8">
<div className="space-y-4">
<div className="flex lg:hidden">
<BreadCrumbs className="text-lg">
APIs
<h2 className="font-body text-lg font-semibold">
{selectedApiEndpoint.api}
</h2>
</BreadCrumbs>
<APIMenu
selected={selectedApiEndpoint}
onAfterClear={() => {
setJSONBody('')
setRequest({
...requestDefault,
method: selectedApiEndpoint.method,
path: generatePath(selectedApiEndpoint.path, [], []),
pathParams: generatePathParams(
selectedApiEndpoint,
requestDefault,
),
})
}}
/>
</div>
<div className="lg:hidden">
<Select
value={selectedApiEndpoint.id}
onValueChange={(id) => {
setSelectedApiEndpoint(paths.find((p) => p.id === id))
}}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select Endpoint" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{paths.map((path) => (
<SelectItem key={path.id} value={path.id}>
<div className="grid grid-cols-12 items-center gap-4 p-0.5 text-lg">
<APIMethodBadge
method={path.method}
className="col-span-3 w-20 px-1.5 !text-lg md:col-span-2"
/>
<div className="col-span-9 flex gap-4 md:col-span-10">
<span>{path?.api}</span>
<span>{path?.path}</span>
</div>
</div>
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-4">
<BreadCrumbs className="hidden text-lg lg:block">
APIs
<h2 className="font-body text-lg font-semibold">
{selectedApiEndpoint.api}
</h2>
<div className="flex items-center gap-4">
<APIMethodBadge
className="!text-lg"
method={request.method}
/>
<span
className="flex gap-2 text-lg"
data-testid="generated-request-path"
>
<Tooltip>
<TooltipTrigger asChild>
<span className="max-w-xl truncate">
{request.path}
</span>
</TooltipTrigger>
<TooltipContent>
<p>{request.path}</p>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => {
copyToClipboard(`${apiAddress}${request.path}`)
toast.success('Copied Route URL')
}}
>
<span className="sr-only">Copy Route URL</span>
<ClipboardIcon className="h-5 w-5 text-muted-foreground" />
</button>
</TooltipTrigger>
<TooltipContent>
<p>Copy Route URL</p>
</TooltipContent>
</Tooltip>
</span>
</div>
</BreadCrumbs>
<div className="ml-auto">
<Button
size="lg"
data-testid="send-api-btn"
onClick={handleSend}
>
Send
</Button>
</div>
</div>
{selectedApiEndpoint.requestingService ? (
<div className={'flex items-center gap-1'}>
<span className="font-semibold">Referenced by:</span>
<div className={'flex items-start gap-1'}>
<Tooltip>
<TooltipTrigger asChild>
<a
data-testid="requesting-service"
className="text-md h-auto p-0 hover:underline"
href={`vscode://file/${data?.services.find((svc) => svc.name === selectedApiEndpoint.requestingService)?.filePath}`}
>
{selectedApiEndpoint.requestingService}
</a>
</TooltipTrigger>
<TooltipContent>
<p>Open in VSCode</p>
</TooltipContent>
</Tooltip>
</div>
</div>
) : null}
{selectedDoesNotExist && (
<NotFoundAlert>
Endpoint not found. It might have been updated or removed.
Select another endpoint.
</NotFoundAlert>
)}
{selectedApiEndpoint.doc.components?.securitySchemes && (
<Alert variant="info">
<div className="flex">
<div className="flex-shrink-0">
<InformationCircleIcon
className="h-5 w-5"
aria-hidden="true"
/>
</div>
<div className="ml-3 flex-1 md:flex md:justify-between">
<p className="text-sm">
Security rules have been applied to this API. These
are not enforced locally. For more information, please
visit our{' '}
<a
href="https://nitric.io/docs/apis#api-security"
target="_blank"
rel="noreferrer"
className="underline text-foreground hover:text-accent-foreground"
>
API Docs
</a>
.
</p>
</div>
</div>
</Alert>
)}
</div>
<SectionCard className="p-0 sm:p-0">
<Tabs
tabs={tabs}
index={currentTabIndex}
setIndex={setCurrentTabIndex}
/>
<SectionCard
className="border-none shadow-none"
title={currentTabName}
>
{currentTabName === 'Params' && (
<ul className="my-4 divide-gray-200">
{request.pathParams.length > 0 && (
<li className="flex flex-col py-4">
<h4 className="text-lg font-medium text-gray-900">
Path Params
</h4>
<FieldRows
lockKeys
testId="path"
valueRequired
rows={request.pathParams}
valueErrors={requiredPathParamErrors}
setRows={(rows) => {
setRequest((prev) => ({
...prev,
pathParams: rows,
}))
}}
/>
</li>
)}
<li className="flex flex-col py-4">
<h4 className="text-lg font-medium text-foreground">
Query Params
</h4>
<FieldRows
rows={request.queryParams}
testId="query"
addRowLabel="Add Query Param"
setRows={(rows) => {
setRequest((prev) => ({
...prev,
queryParams: rows,
}))
}}
/>
</li>
</ul>
)}
{currentTabName === 'Headers' && (
<div className="my-4">
<FieldRows
rows={request.headers}
testId="header"
addRowLabel="Add Header"
setRows={(rows) => {
setRequest((prev) => ({
...prev,
headers: rows,
}))
}}
/>
</div>
)}
{currentTabName === 'Body' && (
<div className="my-4 flex flex-col gap-4">
<Tabs
tabs={reqBodyTypes}
index={bodyTabIndex}
pill
setIndex={setBodyTabIndex}
/>
{currentBodyTab.name === 'JSON' && (
<CodeEditor
id="json-editor"
contentType={currentBodyTab.contentType}
value={JSONBody}
includeLinters
onChange={(value) => {
setJSONBody(value)
}}
/>
)}
{currentBodyTab.name === 'Text' && (
<CodeEditor
id="text-editor"
contentType={currentBodyTab.contentType}
value={textBody}
includeLinters
onChange={(value) => {
setTextBody(value)
}}
/>
)}
{currentBodyTab.name === 'Binary' && (
<div className="mb-2 flex flex-col">
<h4 className="mb-2 text-lg font-medium text-foreground">
Binary File
</h4>
<FileUpload multiple={false} onDrop={onDrop} />
{fileToUpload && (
<span
data-testid="file-upload-info"
className="flex items-center px-4 py-4 sm:px-0 text-muted-foreground"
>
{fileToUpload.name} -{' '}
{formatFileSize(fileToUpload.size)}
</span>
)}
</div>
)}
</div>
)}
</SectionCard>
</SectionCard>
<SectionCard
title="Response"
headerSiblings={
<>
{callLoading && (
<Spinner
className="absolute left-0 top-0 ml-28"
color="info"
size={'md'}
/>
)}
<div className="absolute right-0 top-0 flex gap-2">
{response?.status && (
<Badge
data-testid="response-status"
status={response.status >= 400 ? 'red' : 'green'}
>
Status: {response.status}
</Badge>
)}
{response?.time && (
<Badge data-testid="response-time" status={'green'}>
Time: {formatResponseTime(response.time)}
</Badge>
)}
{typeof response?.size === 'number' && (
<Badge data-testid="response-size" status={'green'}>
Size: {formatFileSize(response.size)}
</Badge>
)}
</div>
</>
}
>
<div className="my-4 max-w-full text-sm">
{response?.data ? (
<div className="flex flex-col gap-4">
<Tabs
tabs={[
{
name: 'Response',
},
{
name: 'Headers',
count: Object.keys(response.headers || {}).length,
},
]}
round
index={responseTabIndex}
setIndex={setResponseTabIndex}
/>
{responseTabIndex === 0 && (
<APIResponseContent response={response} />
)}
{responseTabIndex === 1 && (
<div className="overflow-x-auto">
<div className="inline-block min-w-full py-2 align-middle">
<table className="min-w-full divide-y divide-border">
<thead>
<tr>
<th
scope="col"
className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-foreground sm:pl-6 lg:pl-8"
>
Header
</th>
<th
scope="col"
className="px-3 py-3.5 text-left text-sm font-semibold text-foreground"
>
Value
</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{Object.entries(response.headers || {}).map(
([key, value]) => (
<tr key={key}>
<td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-foreground sm:pl-6 lg:pl-8">
{key}
</td>
<td className="whitespace-nowrap px-3 py-4 text-sm text-muted-foreground">
{value}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
</div>
)}
</div>
) : response ? (
<span className="text-lg text-muted-foreground">
No response data available for this request.
</span>
) : (
<span className="text-lg text-muted-foreground">
Send a request to get a response.
</span>
)}
</div>
</SectionCard>
</div>
<SectionCard
title="Request History"
className="m-0 mb-20 border-none px-0 shadow-none sm:px-0 bg-background"
headerClassName="px-4 sm:px-2"
>
<APIHistory
history={history?.apis ?? []}
selectedRequest={{
path: selectedApiEndpoint.path,
method: request.method,
}}
api={selectedApiEndpoint.api}
apiAddress={apiAddress || 'localhost:4001'}
/>
</SectionCard>
</div>
) : (
<div>
Please refer to our documentation on{' '}
<a
className="underline text-foreground hover:text-accent-foreground"
target="_blank"
href="https://nitric.io/docs/apis"
rel="noreferrer"
>
creating APIs
</a>{' '}
as we are unable to find any existing APIs. <br />
APIs built using{' '}
<a
className="underline text-foreground hover:text-accent-foreground"
target="_blank"
href="https://nitric.io/docs/reference/nodejs/http/http"
rel="noopener noreferrer"
>
the Nitric HTTP Proxy
</a>{' '}
will not appear in this view. You can test these using an external
tool such as cURL, Postman or Insomnia.
</div>
)}
</Loading>
</AppLayout>
)
}
export default APIExplorer