import { RequestError , Response , Options } from "got" ; const got = require ( "got" ) ; const pkg = require ( "../../package.json" ) ; import { StandartParams } from "../interfaces/standart_params" ; import { ClientData } from "../interfaces/client_data" ; export class ApiRequest { private urlRoot : NonNullable < Options [ "prefixUrl" ] > = "https://api.lokalise.com/api2/" ; public promise : Promise < any > ; public params : StandartParams = { } ; constructor ( uri , method , body , params , clientData ) { this . params = params ; this . promise = this . createPromise ( uri , method , body , clientData ) ; return this ; } createPromise ( uri , method , body , clientData ) { const options = { method : method , prefixUrl : this . urlRoot , headers : { "User-Agent" : `node-lokalise-api/${ pkg . version }` , } , agent : false , throwHttpErrors : false , decompress : false , } ; if ( ! options [ "headers" ] ) { options [ "headers" ] = { } ; } options [ "headers" ] [ clientData . authHeader ] = `${ clientData . tokenType } ${ clientData . token }` ; if ( clientData . enableCompression ) { options [ "headers" ] [ "Accept-Encoding" ] = "gzip,deflate" ; options [ "decompress" ] = true ; } const url = this . composeURI ( uri ) ; if ( Object . keys ( this . params ) . length > 0 ) { const formattedParams = new URLSearchParams ( ) ; Object . entries ( this . params ) . forEach ( ( [ key , value ] ) => { formattedParams . set ( key , < string > value ) ; } ) ; options [ "searchParams" ] = formattedParams . toString ( ) ; } if ( method !== "GET" && body ) { options [ "body" ] = JSON . stringify ( body ) ; } return new Promise ( ( resolve , reject ) => { got ( url , options ) . then ( ( response ) => { const responseJSON = JSON . parse ( < string > response . body ) ; if ( response . statusCode > 299 ) { reject ( responseJSON [ "error" ] || responseJSON ) ; return ; } resolve ( { json : responseJSON , headers : response . headers } ) ; return ; } ) . then ( ( error ) => { reject ( error ) ; return error ; } ) . catch ( ( error ) => { reject ( error ) ; return error ; } ) ; } ) ; } protected composeURI ( rawUri ) { const regexp = /{(!{0,1}):(\w*)}/g ; const uri = rawUri . replace ( regexp , this . mapUriParams ( this . params ) ) ; return uri . endsWith ( "/" ) ? uri . slice ( 0 , - 1 ) : uri ; } protected mapUriParams ( params ) { return ( _entity , isMandaratory , paramName ) : string => { if ( params [ paramName ] != null ) { const t_param = params [ paramName ] ; delete this . params [ paramName ] ; return t_param ; } else { if ( isMandaratory == "!" ) { throw new Error ( "Required param " + paramName ) ; } else { return "" ; } } } ; } }