|
| 1 | +import PlayHeader from 'common/playlists/PlayHeader'; |
| 2 | +import { useState, useEffect } from 'react'; |
| 3 | +import RequestPanel from './components/RequestPanel'; |
| 4 | +import ResponsePanel from './components/ResponsePanel'; |
| 5 | +import HistoryPanel from './components/HistoryPanel'; |
| 6 | +import './styles.css'; |
| 7 | + |
| 8 | +function ApiRequestBuilder(props) { |
| 9 | + const [method, setMethod] = useState('GET'); |
| 10 | + const [url, setUrl] = useState('https://jsonplaceholder.typicode.com/posts/1'); |
| 11 | + const [headers, setHeaders] = useState([ |
| 12 | + { key: 'Content-Type', value: 'application/json', enabled: true } |
| 13 | + ]); |
| 14 | + const [body, setBody] = useState(''); |
| 15 | + const [response, setResponse] = useState(null); |
| 16 | + const [isLoading, setIsLoading] = useState(false); |
| 17 | + const [history, setHistory] = useState([]); |
| 18 | + const [activeTab, setActiveTab] = useState('body'); |
| 19 | + const [bodyType, setBodyType] = useState('json'); |
| 20 | + const [showHistory, setShowHistory] = useState(false); |
| 21 | + |
| 22 | + // Load history from localStorage on mount |
| 23 | + useEffect(() => { |
| 24 | + const savedHistory = localStorage.getItem('api-request-history'); |
| 25 | + if (savedHistory) { |
| 26 | + try { |
| 27 | + setHistory(JSON.parse(savedHistory)); |
| 28 | + } catch (error) { |
| 29 | + console.error('Failed to load history:', error); |
| 30 | + } |
| 31 | + } |
| 32 | + }, []); |
| 33 | + |
| 34 | + // Save history to localStorage |
| 35 | + const saveToHistory = (request, response) => { |
| 36 | + const historyItem = { |
| 37 | + id: Date.now(), |
| 38 | + timestamp: new Date().toISOString(), |
| 39 | + method: request.method, |
| 40 | + url: request.url, |
| 41 | + headers: request.headers, |
| 42 | + body: request.body, |
| 43 | + response: { |
| 44 | + status: response.status, |
| 45 | + statusText: response.statusText, |
| 46 | + data: response.data, |
| 47 | + time: response.time, |
| 48 | + size: response.size |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + const updatedHistory = [historyItem, ...history].slice(0, 50); // Keep last 50 requests |
| 53 | + setHistory(updatedHistory); |
| 54 | + localStorage.setItem('api-request-history', JSON.stringify(updatedHistory)); |
| 55 | + }; |
| 56 | + |
| 57 | + const handleSendRequest = async () => { |
| 58 | + if (!url.trim()) { |
| 59 | + setResponse({ |
| 60 | + error: true, |
| 61 | + message: 'Please enter a valid URL', |
| 62 | + status: 0 |
| 63 | + }); |
| 64 | + |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + setIsLoading(true); |
| 69 | + const startTime = Date.now(); |
| 70 | + |
| 71 | + try { |
| 72 | + // Prepare headers |
| 73 | + const requestHeaders = {}; |
| 74 | + headers.forEach((header) => { |
| 75 | + if (header.enabled && header.key.trim()) { |
| 76 | + requestHeaders[header.key] = header.value; |
| 77 | + } |
| 78 | + }); |
| 79 | + |
| 80 | + // Prepare request options |
| 81 | + const options = { |
| 82 | + method: method, |
| 83 | + headers: requestHeaders |
| 84 | + }; |
| 85 | + |
| 86 | + // Add body for methods that support it |
| 87 | + if (['POST', 'PUT', 'PATCH'].includes(method) && body.trim()) { |
| 88 | + if (bodyType === 'json') { |
| 89 | + try { |
| 90 | + JSON.parse(body); // Validate JSON |
| 91 | + options.body = body; |
| 92 | + } catch (e) { |
| 93 | + throw new Error('Invalid JSON in request body'); |
| 94 | + } |
| 95 | + } else { |
| 96 | + options.body = body; |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + const response = await fetch(url, options); |
| 101 | + const endTime = Date.now(); |
| 102 | + const responseTime = endTime - startTime; |
| 103 | + |
| 104 | + let responseData; |
| 105 | + const contentType = response.headers.get('content-type'); |
| 106 | + |
| 107 | + if (contentType && contentType.includes('application/json')) { |
| 108 | + responseData = await response.json(); |
| 109 | + } else { |
| 110 | + responseData = await response.text(); |
| 111 | + } |
| 112 | + |
| 113 | + const responseSize = new Blob([JSON.stringify(responseData)]).size; |
| 114 | + |
| 115 | + const responseObj = { |
| 116 | + status: response.status, |
| 117 | + statusText: response.statusText, |
| 118 | + data: responseData, |
| 119 | + headers: Object.fromEntries(response.headers.entries()), |
| 120 | + time: responseTime, |
| 121 | + size: responseSize, |
| 122 | + error: false |
| 123 | + }; |
| 124 | + |
| 125 | + setResponse(responseObj); |
| 126 | + |
| 127 | + // Save to history |
| 128 | + saveToHistory({ method, url, headers, body }, responseObj); |
| 129 | + } catch (error) { |
| 130 | + setResponse({ |
| 131 | + error: true, |
| 132 | + message: error.message, |
| 133 | + status: 0, |
| 134 | + time: Date.now() - startTime |
| 135 | + }); |
| 136 | + } finally { |
| 137 | + setIsLoading(false); |
| 138 | + } |
| 139 | + }; |
| 140 | + |
| 141 | + const loadFromHistory = (item) => { |
| 142 | + setMethod(item.method); |
| 143 | + setUrl(item.url); |
| 144 | + setHeaders(item.headers); |
| 145 | + setBody(item.body || ''); |
| 146 | + setResponse(item.response); |
| 147 | + setShowHistory(false); |
| 148 | + }; |
| 149 | + |
| 150 | + const clearHistory = () => { |
| 151 | + setHistory([]); |
| 152 | + localStorage.removeItem('api-request-history'); |
| 153 | + }; |
| 154 | + |
| 155 | + const formatJSON = () => { |
| 156 | + try { |
| 157 | + const parsed = JSON.parse(body); |
| 158 | + setBody(JSON.stringify(parsed, null, 2)); |
| 159 | + } catch (error) { |
| 160 | + alert('Invalid JSON format'); |
| 161 | + } |
| 162 | + }; |
| 163 | + |
| 164 | + return ( |
| 165 | + <div className="play-details"> |
| 166 | + <PlayHeader play={props} /> |
| 167 | + <div className="play-details-body"> |
| 168 | + <div className="api-builder-container"> |
| 169 | + <div className="api-builder-header"> |
| 170 | + <h2 className="api-builder-title">🚀 API Request Builder & Tester</h2> |
| 171 | + <button |
| 172 | + className="history-toggle-btn" |
| 173 | + title="View Request History" |
| 174 | + onClick={() => setShowHistory(!showHistory)} |
| 175 | + > |
| 176 | + 📋 History ({history.length}) |
| 177 | + </button> |
| 178 | + </div> |
| 179 | + |
| 180 | + <div className={`api-builder-layout ${showHistory ? 'show-history' : ''}`}> |
| 181 | + <div className="api-builder-main"> |
| 182 | + <RequestPanel |
| 183 | + activeTab={activeTab} |
| 184 | + body={body} |
| 185 | + bodyType={bodyType} |
| 186 | + formatJSON={formatJSON} |
| 187 | + headers={headers} |
| 188 | + isLoading={isLoading} |
| 189 | + method={method} |
| 190 | + setActiveTab={setActiveTab} |
| 191 | + setBody={setBody} |
| 192 | + setBodyType={setBodyType} |
| 193 | + setHeaders={setHeaders} |
| 194 | + setMethod={setMethod} |
| 195 | + setUrl={setUrl} |
| 196 | + url={url} |
| 197 | + onSend={handleSendRequest} |
| 198 | + /> |
| 199 | + |
| 200 | + <ResponsePanel isLoading={isLoading} response={response} /> |
| 201 | + </div> |
| 202 | + |
| 203 | + {showHistory && ( |
| 204 | + <HistoryPanel |
| 205 | + history={history} |
| 206 | + onClearHistory={clearHistory} |
| 207 | + onClose={() => setShowHistory(false)} |
| 208 | + onLoadRequest={loadFromHistory} |
| 209 | + /> |
| 210 | + )} |
| 211 | + </div> |
| 212 | + </div> |
| 213 | + </div> |
| 214 | + </div> |
| 215 | + ); |
| 216 | +} |
| 217 | + |
| 218 | +export default ApiRequestBuilder; |
0 commit comments