UNPKG

@remote.it/core

Version:

Core remote.it JavasScript/TypeScript library

85 lines (69 loc) 2.02 kB
import debug from 'debug' import axios, { Method, AxiosError, AxiosResponse } from 'axios' import { Logger } from './Logger' const d = debug('remoteit:API') const API_URL = 'https://api01.remot3.it/apv/v27' const API_KEY = 'remote.it.developertoolsHW9iHnd' export class API { static token?: string // constructor(args: { token?: string }) { // this.token = args.token // } static post<T>(url: string, data?: any) { return this.request<T>('post', url, data) } static get<T>(url: string) { return this.request<T>('get', url) } private static request<T>( method: Method, url: string, data?: any ): Promise<T> { // if (!this.token) throw new Error('No authentication token provided!') const headers: any = { apikey: API_KEY, 'Content-Type': 'application/json' } if (this.token) headers.token = this.token const request = { method, url: API_URL + url, data, headers, } return axios .request<T>(request) .then(d => this.processData(d), e => this.processError(e)) .catch((error: AxiosError) => { const data: any = { message: error.message, method: request.method, url: request.url, data: request.data, headers: request.headers, } if (error.response) { data.body = error.response.config.data data.response = error.response.data } d('request error:', data) Logger.error('request error', data) throw error }) } private static processData(resp: AxiosResponse | any = {}) { if ( resp.data && resp.data.status && resp.data.reason && resp.data.status === 'false' ) { throw new Error(resp.data.reason) } return resp.data } private static processError(error: AxiosError) { if (error.response && error.response.data && error.response.data.reason) { error.message = error.response.data.reason } throw error } }