SemanticApi.ts (1330B)
1 import { requestUrl, RequestUrlParam, RequestUrlResponsePromise } from "obsidian"; 2 import pDebounce from 'p-debounce'; 3 4 const baseURL: string = "https://api.semanticscholar.org/graph/v1"; 5 6 export interface BaseRequest { 7 method?: string; 8 contentType?: string; 9 body?: string | ArrayBuffer; 10 headers?: Record<string, string>; 11 } 12 13 export class SemanticApi { 14 key?: string; 15 16 constructor(key?: string) { 17 this.key = key; 18 } 19 20 request(endpoint: string, params: Record<string, string>, base?: BaseRequest): RequestUrlResponsePromise { 21 var paramsList: string[] = []; 22 for (let key in params) { 23 paramsList.push(`${key}=${encodeURIComponent(params[key])}`) 24 } 25 26 var headers: Record<string,string> = base ? (base.headers ? base.headers : {}) : {}; 27 if (this.key) { 28 headers['x-api-key'] = this.key; 29 } 30 31 var req: RequestUrlParam = { 32 url: `${baseURL}/${endpoint}?${paramsList.join('&')}`, 33 method: base ? base.method : undefined, 34 headers: headers, 35 body: base ? base.body : undefined, 36 contentType: base ? base.contentType : undefined, 37 }; 38 console.log("Requesting", req); 39 return requestUrl(req) 40 } 41 42 debouncedRequest = pDebounce(this.request, 1000) 43 }