2019-12-21 18:44:56 -08:00
|
|
|
import { OptionsWithUri } from 'request';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IExecuteFunctions,
|
2020-10-01 05:01:39 -07:00
|
|
|
IExecuteSingleFunctions,
|
2019-12-21 18:44:56 -08:00
|
|
|
IHookFunctions,
|
|
|
|
ILoadOptionsFunctions,
|
2019-12-31 12:19:37 -08:00
|
|
|
IPollFunctions,
|
2019-12-21 18:44:56 -08:00
|
|
|
ITriggerFunctions,
|
|
|
|
} from 'n8n-core';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IDataObject,
|
|
|
|
} from 'n8n-workflow';
|
|
|
|
|
2019-12-31 12:19:37 -08:00
|
|
|
export async function togglApiRequest(this: ITriggerFunctions | IPollFunctions | IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query?: IDataObject, uri?: string): Promise<any> { // tslint:disable-line:no-any
|
2019-12-21 18:44:56 -08:00
|
|
|
const credentials = this.getCredentials('togglApi');
|
|
|
|
if (credentials === undefined) {
|
|
|
|
throw new Error('No credentials got returned!');
|
|
|
|
}
|
|
|
|
const headerWithAuthentication = Object.assign({},
|
2019-12-31 12:19:37 -08:00
|
|
|
{ Authorization: ` Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}` });
|
2019-12-21 18:44:56 -08:00
|
|
|
|
|
|
|
const options: OptionsWithUri = {
|
|
|
|
headers: headerWithAuthentication,
|
|
|
|
method,
|
|
|
|
qs: query,
|
|
|
|
uri: uri || `https://www.toggl.com/api/v8${resource}`,
|
|
|
|
body,
|
|
|
|
json: true
|
|
|
|
};
|
|
|
|
if (Object.keys(options.body).length === 0) {
|
|
|
|
delete options.body;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
return await this.helpers.request!(options);
|
|
|
|
} catch (error) {
|
2019-12-31 12:19:37 -08:00
|
|
|
if (error.statusCode === 403) {
|
|
|
|
throw new Error('The Toggle credentials are probably invalid!');
|
|
|
|
}
|
2019-12-21 18:44:56 -08:00
|
|
|
|
2019-12-31 12:19:37 -08:00
|
|
|
const errorMessage = error.response.body && (error.response.body.message || error.response.body.Message);
|
2019-12-21 18:44:56 -08:00
|
|
|
if (errorMessage !== undefined) {
|
2019-12-31 12:19:37 -08:00
|
|
|
throw new Error(errorMessage);
|
2019-12-21 18:44:56 -08:00
|
|
|
}
|
2019-12-31 12:19:37 -08:00
|
|
|
|
|
|
|
throw error;
|
2019-12-21 18:44:56 -08:00
|
|
|
}
|
|
|
|
}
|