Download src/lib/http.ts from IOE-IFAD/test: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/spaces/IOE-IFAD/test/resolve/main/src/lib/http.ts
- Command line
-
hf download hf://spaces/IOE-IFAD/test/src/lib/http.ts
-
curl -L -o http.ts https://huggingface.co/spaces/IOE-IFAD/test/resolve/main/src/lib/http.ts
2.2 kB
| // Import necessary types from TypeScript and fetch API | |
| const port = 8000; | |
| // const baseUrl = `https://obscure-spork-jr94576rpr53wgg-8000.app.github.dev/api/v1`; | |
| // const baseUrl = `http://localhost:${port}/api/v1`; | |
| const baseUrl = `/api/v1`; | |
| // Define types for the request function parameters | |
| type RequestMethod = "GET" | "POST" | "PUT" | "DELETE"; | |
| interface RequestHeaders { | |
| [key: string]: string; | |
| } | |
| interface RequestOptions { | |
| method: RequestMethod; | |
| url: string; | |
| data?: any; // Data can be of any type, though usually it's JSON or FormData | |
| headers?: RequestHeaders; | |
| bearerToken?: string | null; | |
| } | |
| // Utility function to handle requests | |
| export async function request( | |
| method: RequestMethod, | |
| url: string, | |
| data: any = null, | |
| headers: RequestHeaders = {}, | |
| bearerToken: string | null = null | |
| ): Promise<Response> { | |
| url = baseUrl + url; | |
| // Define headers and options for the fetch API | |
| let fetchOptions: RequestInit = { | |
| method: method, | |
| headers: { | |
| "Content-Type": "application/json", | |
| Authorization: bearerToken ? `Bearer ${bearerToken}` : "", | |
| ...headers, | |
| }, | |
| }; | |
| // Adjust the Content-Type if data is FormData | |
| if (data instanceof FormData) { | |
| delete (fetchOptions.headers as Record<string, string>)["Content-Type"]; | |
| } | |
| // Set request body if data is present | |
| if (data !== null) { | |
| fetchOptions.body = data instanceof FormData ? data : JSON.stringify(data); | |
| } | |
| // Send the request and return the fetch response | |
| return fetch(url, fetchOptions); | |
| } | |
| // Define individual HTTP method functions | |
| export function get( | |
| url: string, | |
| headers?: RequestHeaders, | |
| bearerToken?: string | |
| ) { | |
| return request("GET", url, null, headers, bearerToken); | |
| } | |
| export function post( | |
| url: string, | |
| data: any, | |
| headers?: RequestHeaders, | |
| bearerToken?: string | |
| ) { | |
| return request("POST", url, data, headers, bearerToken); | |
| } | |
| export function put( | |
| url: string, | |
| data: any, | |
| headers?: RequestHeaders, | |
| bearerToken?: string | |
| ) { | |
| return request("PUT", url, data, headers, bearerToken); | |
| } | |
| export function del( | |
| url: string, | |
| headers?: RequestHeaders, | |
| bearerToken?: string | |
| ) { | |
| return request("DELETE", url, null, headers, bearerToken); | |
| } | |