import axios , { AxiosRequestConfig , Method } from 'axios' ; import { IDataObject , } from 'n8n-workflow' ; import { IRestApiContext , } from '../Interface' ; class ResponseError extends Error { httpStatusCode ? : number ; errorCode ? : number ; serverStackTrace ? : string ; param { string } message param { number } errorCode param { number } httpStatusCode param { string } stack memberof constructor ( message , options = { } ) { super ( message ) ; this . name = 'ResponseError' ; const { errorCode , httpStatusCode , stack } = options ; if ( errorCode ) { this . errorCode = errorCode ; } if ( httpStatusCode ) { this . httpStatusCode = httpStatusCode ; } if ( stack ) { this . serverStackTrace = stack ; } } } async function request ( config ) { const { method , baseURL , endpoint , headers , data } = config ; const options = { method , url : endpoint , baseURL , headers , } ; if ( [ 'PATCH' , 'POST' , 'PUT' ] . includes ( method ) ) { options . data = data ; } else { options . params = data ; } try { const response = await axios . request ( options ) ; return response . data ; } catch ( error ) { if ( error . message === 'Network Error' ) { throw new ResponseError ( 'API-Server can not be reached. It is probably down.' ) ; } const errorResponseData = error . response . data ; if ( errorResponseData !== undefined && errorResponseData . message !== undefined ) { if ( errorResponseData . name === 'NodeApiError' ) { errorResponseData . httpStatusCode = error . response . status ; throw errorResponseData ; } throw new ResponseError ( errorResponseData . message , { errorCode : errorResponseData . code , httpStatusCode : error . response . status , stack : errorResponseData . stack } ) ; } throw error ; } } export async function makeRestApiRequest ( context , method , endpoint , data ? ) { const response = await request ( { method , baseURL : context . baseUrl , endpoint , headers : { sessionid : context . sessionId } , data , } ) ; return response . data ; } export async function get ( baseURL , endpoint , params ? , headers ? ) { return await request ( { method : 'GET' , baseURL , endpoint , headers , data : params } ) ; } export async function post ( baseURL , endpoint , params ? , headers ? ) { return await request ( { method : 'POST' , baseURL , endpoint , headers , data : params } ) ; }