import fetch , { RequestInit } from 'node-fetch' ; import { wikiError } from './errors' ; let API_URL = 'https://en.wikipedia.org/w/api.php?' , REST_API_URL = 'https://en.wikipedia.org/api/rest_v1/' ; const USER_AGENT = 'wikipedia (https://github.com/dopecodez/Wikipedia/)' ; async function makeRequest ( params , redirect = true ) { try { const search = { ... params } ; search [ 'format' ] = 'json' ; if ( redirect ) { search [ 'redirects' ] = '' ; } if ( ! params . action ) search [ 'action' ] = "query" ; search [ 'origin' ] = '*' ; const options = { headers : { 'User-Agent' : USER_AGENT , } } ; let searchParam = '' ; Object . keys ( search ) . forEach ( key => { searchParam += `${ key }=${ search [ key ] }&` ; } ) ; const response = await fetch ( encodeURI ( API_URL + searchParam ) , options ) ; const result = await response . json ( ) ; return result ; } catch ( error ) { throw new wikiError ( error ) ; } } export async function makeRestRequest ( path , redirect = true ) { try { if ( ! redirect ) { path += '?redirect=false' ; } const options = { headers : { 'User-Agent' : USER_AGENT } } ; console . log ( encodeURI ( REST_API_URL + path ) ) ; const response = await fetch ( encodeURI ( REST_API_URL + path ) , options ) ; let result = await response . text ( ) ; try { result = JSON . parse ( result ) ; } finally { return result ; } } catch ( error ) { throw new wikiError ( error ) ; } } export function returnRestUrl ( path ) { const url = encodeURI ( REST_API_URL + path ) ; return url ; } export function setAPIUrl ( prefix ) { API_URL = 'https://' + prefix . toLowerCase ( ) + '.wikipedia.org/w/api.php?' ; REST_API_URL = 'https://' + prefix . toLowerCase ( ) + '.wikipedia.org/api/rest_v1/' ; return API_URL ; } export default makeRequest ;