Преглед изворни кода

small fixes and renderer fixes

tonyboylehub пре 11 месеци
родитељ
комит
8ec1800e45

+ 5 - 5
src/components/apiComponents/endPointSelector.jsx

@@ -16,7 +16,7 @@ const endPoints = {
   },
 }
 
-const EndPointSelector = ({ setActiveEndpoint }) => {
+const EndPointSelector = ({ setActiveEndpoint, activeEndpoint }) => {
   const [isCustom, setIsCustom] = useState(false)
   const [customEndPoint, setCustomEndPoint] = useState('')
 
@@ -49,7 +49,7 @@ const EndPointSelector = ({ setActiveEndpoint }) => {
         className="text-sm font-medium text-gray-800 dark:text-neutral-400"
         htmlFor="endPoint"
       >
-        End Point
+        Endpoint
       </label>
       <div className="relative flex h-12 w-full">
         <Select
@@ -74,7 +74,7 @@ const EndPointSelector = ({ setActiveEndpoint }) => {
           aria-hidden="true"
         />
       </div>
-      {isCustom && (
+    
         <input
           type="text"
           name="customEndPoint"
@@ -84,9 +84,9 @@ const EndPointSelector = ({ setActiveEndpoint }) => {
             handleSelectEndpoint(e)
             localStorage.setItem('customEndPoint', e.target.value)
           }}
-          value={customEndPoint}
+          disabled={!isCustom}
+          value={isCustom ? customEndPoint : activeEndpoint}
         />
-      )}
     </div>
   )
 }

+ 14 - 25
src/components/apiComponents/languageComponents/cSharpRenderer.jsx

@@ -1,32 +1,25 @@
-const { Fence } = require('@/components/Fence')
-const { default: renderRequestBody } = require('@/lib/api/renderRequestBody')
+const { Fence } = require('@/components/Fence');
 
 const CSharpRequestRenderer = ({
   url,
-  headers = {}, // Headers are passed as a prop
   bodyMethod,
   rpcVersion,
   bodyParams,
   id,
 }) => {
-  const httpBody = bodyParams
+  const httpBody = bodyParams;
 
   const object = {
     method: 'POST',
-    headers: headers,
     body: {
       jsonrpc: rpcVersion ? rpcVersion : '2.0',
       id: id ? id : 1,
       method: bodyMethod,
       params: httpBody,
     },
-  }
-
-  const headersCode = Object.entries(headers)
-    .map(([key, value]) => `{"${key}", "${value}"}`)
-    .join(',\n      ')
+  };
 
-  const jsonBody = JSON.stringify(object.body, null, 2).replace(/"/g, '""')
+  const jsonBody = JSON.stringify(object.body, null, 2).replace(/"/g, '""');
 
   const code = `
 using System;
@@ -37,9 +30,6 @@ class Program
 {
   static void Main() {
     var url = "${url}";
-    var headers = new System.Collections.Generic.Dictionary<string, string> {
-      ${headersCode}
-    };
     var data = new StringContent(@"
     ${jsonBody.replace(/\n/g, '\n    ')}
     ", Encoding.UTF8, "application/json");
@@ -51,22 +41,21 @@ class Program
       Content = data
     };
 
-    foreach (var header in headers) {
-      request.Headers.Add(header.Key, header.Value);
+    try {
+      var response = client.SendAsync(request).Result;
+      Console.WriteLine($"Status Code: {response.StatusCode}");
+      Console.WriteLine(response.Content.ReadAsStringAsync().Result);
+    } catch (Exception ex) {
+      Console.WriteLine($"An error occurred: {ex.Message}");
     }
-
-    var response = client.SendAsync(request).Result;
-
-    Console.WriteLine(response.StatusCode);
   }
-}
-`
+}`;
 
   return (
     <Fence maxHeight={400} language="csharp">
       {code}
     </Fence>
-  )
-}
+  );
+};
 
-export default CSharpRequestRenderer
+export default CSharpRequestRenderer;

+ 30 - 5
src/components/apiComponents/languageComponents/goRequestRenderer.jsx

@@ -34,7 +34,9 @@ const GoRequestRenderer = ({
 import (
   "bytes"
   "fmt"
+  "io/ioutil"
   "net/http"
+  "time"
 )
 
 func main() {
@@ -47,22 +49,45 @@ ${headersCode}
 
   req, err := http.NewRequest("POST", url, data)
   if err != nil {
-    fmt.Println(err)
+    fmt.Printf("Error creating request: %v\\n", err)
+    return
   }
 
   for key, value := range headers {
     req.Header.Set(key, value)
   }
 
-  client := &http.Client{}
+  // Create an HTTP client with a timeout
+  client := &http.Client{
+    Timeout: 10 * time.Second,
+  }
+
+  // Send the request
   resp, err := client.Do(req)
   if err != nil {
-    fmt.Println(err)
+    fmt.Printf("Error making request to %s: %v\\n", url, err)
+    return
   }
 
-  defer resp.Body.Close()
+  // Ensure response body is closed
+  defer func() {
+    if resp != nil && resp.Body != nil {
+      resp.Body.Close()
+    }
+  }()
+
+  // Print the status code
+  fmt.Println("Status:", resp.Status)
+
+  // Read the response body
+  body, err := ioutil.ReadAll(resp.Body)
+  if err != nil {
+    fmt.Printf("Error reading response body: %v\\n", err)
+    return
+  }
 
-  fmt.Println(resp.Status)
+  // Print the response body
+  fmt.Println("Response Body:", string(body))
 }
 `
 

+ 16 - 2
src/components/apiComponents/languageComponents/javaRenderer.jsx

@@ -27,9 +27,11 @@ const JavaRequestRenderer = ({
     .join('\n')
 
   // Format the JSON body correctly for the Java code with proper indentation
-  const jsonBody = JSON.stringify(object.body, null, 2) // 4-space indentation for JSON
+  const jsonBody = JSON.stringify(object.body, null, 2)
 
-  const code = `import java.io.OutputStream;
+  const code = `import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;
 
@@ -64,7 +66,19 @@ public class Main {
             int responseCode = con.getResponseCode();
             System.out.println("Response Code: " + responseCode);
 
+            // Read the response body
+            try (BufferedReader br = new BufferedReader(
+                    new InputStreamReader(con.getInputStream(), "utf-8"))) {
+                StringBuilder response = new StringBuilder();
+                String responseLine;
+                while ((responseLine = br.readLine()) != null) {
+                    response.append(responseLine.trim());
+                }
+                System.out.println("Response Body: " + response.toString());
+            }
+
         } catch (Exception e) {
+            System.err.println("Error occurred while making the request:");
             e.printStackTrace();
         }
     }

+ 24 - 16
src/components/apiComponents/languageComponents/phpRenderer.jsx

@@ -3,30 +3,38 @@ import { Fence } from '@/components/Fence';
 const PhpRequestRenderer = ({ url, headers, bodyMethod, rpcVersion, bodyParams, id }) => {
   const httpBody = bodyParams;
 
-  const object = {
-    method: 'POST',
-    headers: headers,
-    body: {
-      jsonrpc: rpcVersion ? rpcVersion : '2.0',
-      id: id ? id : 1,
-      method: bodyMethod,
-      params: httpBody,
-    },
+  // Handle default values for `rpcVersion` and `id`
+  const rpcVersionValue = rpcVersion || '2.0';
+  const idValue = id || 1;
+
+  // Convert httpBody to a PHP-compatible format
+  const formatParamsForPhp = (params) => {
+    if (Array.isArray(params)) {
+      return `[${params.map(item => `'${item}'`).join(', ')}]`; // Correct array formatting for PHP
+    }
+    if (typeof params === 'object') {
+      return `[${Object.entries(params)
+        .map(([key, value]) => `'${key}' => '${value}'`)
+        .join(', ')}]`; // Use PHP array syntax for key-value pairs
+    }
+    return `'${params}'`;
   };
 
+  const formattedParams = formatParamsForPhp(httpBody);
+
   const headersCode = Object.entries(headers)
-    .map(([key, value]) => `"${key}" => "${value}"`)
-    .join(",\n        ");
+    .map(([key, value]) => `"${key}: ${value}"`)
+    .join(",\n    ");
 
   const code = `
 <?php
 
 $url = "${url}";
 $data = [
-    "jsonrpc" => "${rpcVersion ? rpcVersion : '2.0'}",
-    "id" => ${id ? id : 1},
+    "jsonrpc" => "${rpcVersionValue}",
+    "id" => ${idValue},
     "method" => "${bodyMethod}",
-    "params" => ${JSON.stringify(httpBody, null, 2).replace(/\n/g, '\n    ')}
+    "params" => ${formattedParams}
 ];
 
 // Initialize cURL session
@@ -35,7 +43,7 @@ $ch = curl_init($url);
 // Set cURL options
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POST, true);
-curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
 curl_setopt($ch, CURLOPT_HTTPHEADER, [
     "Content-Type: application/json",
     ${headersCode}
@@ -45,7 +53,7 @@ curl_setopt($ch, CURLOPT_HTTPHEADER, [
 $response = curl_exec($ch);
 
 // Check for errors
-if($response === false) {
+if ($response === false) {
     echo "cURL Error: " . curl_error($ch);
 } else {
     echo "Response: " . $response;

+ 22 - 13
src/components/apiComponents/languageComponents/pythonRequestRenderer.jsx

@@ -3,19 +3,28 @@ import { Fence } from '@/components/Fence';
 const PythonRequestRenderer = ({ url, headers, bodyMethod, rpcVersion, bodyParams, id }) => {
   const httpBody = bodyParams;
 
-  const object = {
-    method: 'POST',
-    headers: headers,
-    body: {
-      jsonrpc: rpcVersion ? rpcVersion : '2.0',
-      id: id ? id : 1,
-      method: bodyMethod,
-      params: httpBody,
-    },
+  // Handle default values for `rpcVersion` and `id`
+  const rpcVersionValue = rpcVersion || '2.0';
+  const idValue = id || 1;
+
+  // Function to format params as Python-style dictionaries
+  const formatParamsForPython = (params) => {
+    if (Array.isArray(params)) {
+      return `[${params.map(item => `'${item}'`).join(', ')}]`; // Correct array formatting for Python
+    }
+    if (typeof params === 'object') {
+      return `{${Object.entries(params)
+        .map(([key, value]) => `'${key}': '${value}'`)
+        .join(', ')}}`; // Use Python dict syntax for key-value pairs
+    }
+    return `'${params}'`;
   };
 
+  const formattedParams = formatParamsForPython(httpBody);
+
+  // Convert headers to Python dict format
   const headersCode = Object.entries(headers)
-    .map(([key, value]) => `"${key}": "${value}"`)
+    .map(([key, value]) => `'${key}': '${value}'`)
     .join(",\n    ");
 
   const code = `
@@ -30,10 +39,10 @@ headers = {
 }
 
 data = {
-    "jsonrpc": "${rpcVersion ? rpcVersion : '2.0'}",
-    "id": ${id ? id : 1},
+    "jsonrpc": "${rpcVersionValue}",
+    "id": ${idValue},
     "method": "${bodyMethod}",
-    "params": ${JSON.stringify(httpBody, null, 2).replace(/\n/g, '\n    ')}
+    "params": ${formattedParams}
 }
 
 response = requests.post(url, headers=headers, data=json.dumps(data))

+ 4 - 1
src/components/apiComponents/languageComponents/rubyRenderer.jsx

@@ -4,7 +4,7 @@ const RubyRequestRenderer = ({ url, headers, bodyMethod, rpcVersion, bodyParams,
   const httpBody = bodyParams;
 
   const headersCode = Object.entries(headers)
-    .map(([key, value]) => `    req["${key}"] = "${value}"`)
+    .map(([key, value]) => `    request["${key}"] = "${value}"`)
     .join("\n");
 
   const code = `
@@ -12,7 +12,10 @@ require 'net/http'
 require 'json'
 require 'uri'
 
+# Parse the URL
 uri = URI.parse("${url}")
+uri.path = uri.path.empty? ? "/" : uri.path  # Ensure the path is not empty
+
 http = Net::HTTP.new(uri.host, uri.port)
 
 # Prepare the request body

+ 1 - 3
src/components/apiComponents/languageComponents/rustRenderer.jsx

@@ -31,11 +31,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
         params: serde_json::json!(${JSON.stringify(httpBody)}),
     };
 
-    let mut request = client.post(url)
+    let request = client.post(url)
         .header(CONTENT_TYPE, "application/json");
 
-    ${headersCode}
-
     let response = request.json(&request_body).send()?;
 
     println!("Response: {:?}", response.text()?);

+ 7 - 2
src/components/apiComponents/languageComponents/swiftRenderer.jsx

@@ -32,11 +32,16 @@ request.httpBody = jsonData
 
 let task = URLSession.shared.dataTask(with: request) { data, response, error in
     if let error = error {
-        print("Error: \(error)")
+        print("Error: \(error.localizedDescription)")
         return
     }
+
+    if let response = response as? HTTPURLResponse {
+        print("Response Status Code: \(response.statusCode)")
+    }
+
     if let data = data, let responseString = String(data: data, encoding: .utf8) {
-        print("Response: \(responseString)")
+        print("Response Body: \(responseString)")
     }
 }
 

+ 17 - 16
src/components/apiComponents/languageRenderer.jsx

@@ -99,7 +99,7 @@ const LanguageRenderer = ({ api, body, setActiveEndPoint, activeEndPoint }) => {
             <CSharpRequestRenderer
               method={api.method}
               url={activeEndPoint}
-              headers={headers}
+              // headers={headers}
               bodyMethod={body.method}
               bodyParams={body.params}
             />
@@ -137,21 +137,21 @@ const LanguageRenderer = ({ api, body, setActiveEndPoint, activeEndPoint }) => {
             />
           </div>
         )
-      case 'kotlin':
-        return (
-          <div className="flex flex-col">
-            <div className="-mb-3 text-sm font-medium text-gray-800 dark:text-neutral-400">
-              {strToTitleCase(activeLanguage)} Request Example
-            </div>
-            <KotlinRenderer
-              method={api.method}
-              url={activeEndPoint}
-              headers={headers}
-              bodyMethod={body.method}
-              bodyParams={body.params}
-            />
-          </div>
-        )
+      // case 'kotlin':
+      //   return (
+      //     <div className="flex flex-col">
+      //       <div className="-mb-3 text-sm font-medium text-gray-800 dark:text-neutral-400">
+      //         {strToTitleCase(activeLanguage)} Request Example
+      //       </div>
+      //       <KotlinRenderer
+      //         method={api.method}
+      //         url={activeEndPoint}
+      //         headers={headers}
+      //         bodyMethod={body.method}
+      //         bodyParams={body.params}
+      //       />
+      //     </div>
+      //   )
       case 'ruby':
         return (
           <div className="flex flex-col">
@@ -204,6 +204,7 @@ const LanguageRenderer = ({ api, body, setActiveEndPoint, activeEndPoint }) => {
     <div className="flex w-full flex-col gap-8 overflow-hidden">
       <EndPointSelector
         setActiveEndpoint={(endpoint) => setActiveEndPoint(endpoint)}
+        activeEndpoint={activeEndPoint}
       />
       <LanguageSelector
         activeLanguage={activeLanguage}

+ 19 - 22
src/components/apiComponents/languageSelector.jsx

@@ -1,19 +1,17 @@
 import { Icon } from '@/components/icons'
 
 const languages = [
+  { name: 'curl', icon: 'CurlIcon' },
   { name: 'javascript', icon: 'JavaScriptIcon' },
   { name: 'python', icon: 'PythonIcon' },
-  { name: 'ruby', icon: 'RubyIcon' },
+  { name: 'php', icon: 'PhpIcon' },
   { name: 'go', icon: 'GoIcon' },
+  { name: 'ruby', icon: 'RubyIcon' },
+  // { name: 'kotlin', icon: 'KotlinIcon' },
   { name: 'java', icon: 'JavaIcon' },
-  { name: 'csharp', icon: 'CSharpIcon' },
   { name: 'swift', icon: 'SwiftIcon' },
-  { name: 'kotlin', icon: 'KotlinIcon' },
-  { name: 'php', icon: 'PhpIcon' },
-  // { name: 'typescript', icon: 'TypescriptIcon' },
-  { name: 'shell', icon: 'ShellIcon' },
-  { name: 'curl', icon: 'CurlIcon' },
   { name: 'rust', icon: 'RustIcon' },
+  { name: 'csharp', icon: 'CSharpIcon' },
 ]
 
 const LanguageSelector = ({ activeLanguage, setActiveLanguage }) => {
@@ -23,21 +21,20 @@ const LanguageSelector = ({ activeLanguage, setActiveLanguage }) => {
         Language
       </div>
       <div className="flex overflow-auto">
-        {languages
-          .sort((a, b) => a.name.localeCompare(b.name))
-          .map((language) => (
-            <button
-              key={language.name}
-              className={`min-w-16 -ms-px inline-flex flex-col items-center justify-center gap-1 border border-gray-200 px-10 py-2 text-xs font-medium text-gray-800 shadow-sm transition-colors first:ms-0 first:rounded-s-lg last:rounded-e-lg hover:bg-gray-50 focus:z-10 focus:bg-accent-300 focus:outline-none focus:ring-1 disabled:pointer-events-none disabled:opacity-50 dark:border-neutral-700 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800 ${activeLanguage === language.name
-                  ? 'bg-accent-300 text-black hover:bg-accent-300 dark:bg-accent-300 dark:text-black dark:hover:bg-accent-300'
-                  : ''
-                }`}
-              onClick={() => setActiveLanguage(language.name)}
-            >
-              <Icon icon={language.icon} className="h-4 w-4" />
-              {language.name}
-            </button>
-          ))}
+        {languages.map((language) => (
+          <button
+            key={language.name}
+            className={`-ms-px inline-flex min-w-16 flex-col items-center justify-center gap-1 border border-gray-200 px-10 py-2 text-xs font-medium text-gray-800 shadow-sm transition-colors first:ms-0 first:rounded-s-lg last:rounded-e-lg hover:bg-gray-50 focus:z-10 focus:bg-accent-300 focus:outline-none focus:ring-1 disabled:pointer-events-none disabled:opacity-50 dark:border-neutral-700 dark:bg-neutral-900 dark:text-white dark:hover:bg-neutral-800 ${
+              activeLanguage === language.name
+                ? 'bg-accent-300 text-black hover:bg-accent-300 dark:bg-accent-300 dark:text-black dark:hover:bg-accent-300'
+                : ''
+            }`}
+            onClick={() => setActiveLanguage(language.name)}
+          >
+            <Icon icon={language.icon} className="h-4 w-4" />
+            {language.name}
+          </button>
+        ))}
       </div>
     </div>
   )

+ 1 - 1
src/pages/aura/api/v1/das/get-asset.md

@@ -4,6 +4,6 @@ metaTitle: Get Asset Method | Aura API
 description: Learn about the Get Asset Aura API Method.
 ---
 
-Fetch a NFT Digital Asset from the Solana blockchain including NFTs, pNFTs, cNFTs.
+Fetch an NFT Digital Asset from the Solana blockchain including NFTs, pNFTs, cNFTs.
 
 {% apiRenderer method="getAsset" /%}