import { queryEncode , createPayload } from '../util' ; import { DEFAULT_RETRIES } from '../config' ; export default class BaseAPI { static API_ENDPOINT = 'https://slack.com/api/' ; constructor ( protected _token = null , private _retries_limit = DEFAULT_RETRIES ) { } protected _get ( api , args = { } ) { const encodedArgs = queryEncode ( { token : this . _token , ... args } ) ; const url = `${ BaseAPI . API_ENDPOINT }${ api }?${ encodedArgs }` ; const params = { method : 'get' , contentType : 'application/x-www-form-urlencoded; charset=UTF-8' } ; return this . _fetch ( url , params ) ; } protected _post ( api , args = { } ) { const payload = createPayload ( { ... args } ) ; const url = `${ BaseAPI . API_ENDPOINT }${ api }` ; const params = { headers : { Authorization : `Bearer ${ this . _token }` } , method : 'post' , contentType : 'application/json; charset=UTF-8' , payload : JSON . stringify ( payload ) } ; return this . _fetch ( url , params ) ; } protected _post_file ( api , file_args , args = { } ) { const payload = createPayload ( { ... args } ) ; const url = `${ BaseAPI . API_ENDPOINT }${ api }?` ; const params = { headers : { Authorization : `Bearer ${ this . _token }` } , method : 'post' , contentType : 'multipart/form-data; charset=UTF-8' , payload : { ... file_args , ... payload } } ; return this . _fetch ( url , params ) ; } protected _fetch ( url , params = null ) { let response = null ; for ( let retry = 0 ; retry < this . _retries_limit ; retry ++ ) { try { response = UrlFetchApp . fetch ( url , params ) ; } catch ( e ) { throw e ; } if ( response . getResponseCode ( ) === 429 ) { Utilities . sleep ( parseInt ( response . getHeaders ( ) [ 'retry-after' ] ) ) ; continue ; } return response ; } throw Error ( 'Try limit over' ) ; } }