2020-02-28 16:55:14 -08:00
|
|
|
import { OptionsWithUri } from 'request';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IExecuteFunctions,
|
|
|
|
ILoadOptionsFunctions,
|
|
|
|
} from 'n8n-core';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IDataObject,
|
|
|
|
IHookFunctions,
|
|
|
|
IWebhookFunctions
|
|
|
|
} from 'n8n-workflow';
|
|
|
|
|
|
|
|
export async function driftApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
|
|
|
|
let options: OptionsWithUri = {
|
2020-06-16 02:45:47 -07:00
|
|
|
headers: {},
|
2020-02-28 16:55:14 -08:00
|
|
|
method,
|
|
|
|
body,
|
|
|
|
qs: query,
|
2020-06-16 02:45:47 -07:00
|
|
|
uri: uri || `https://driftapi.com${resource}`,
|
2020-10-22 06:46:03 -07:00
|
|
|
json: true,
|
2020-02-28 16:55:14 -08:00
|
|
|
};
|
2020-06-16 02:45:47 -07:00
|
|
|
|
2020-02-28 16:55:14 -08:00
|
|
|
if (!Object.keys(body).length) {
|
|
|
|
delete options.form;
|
|
|
|
}
|
|
|
|
if (!Object.keys(query).length) {
|
|
|
|
delete options.qs;
|
|
|
|
}
|
|
|
|
options = Object.assign({}, options, option);
|
2020-06-16 02:45:47 -07:00
|
|
|
|
|
|
|
const authenticationMethod = this.getNodeParameter('authentication', 0);
|
|
|
|
|
2020-02-28 16:55:14 -08:00
|
|
|
try {
|
2020-06-16 02:45:47 -07:00
|
|
|
if (authenticationMethod === 'accessToken') {
|
|
|
|
const credentials = this.getCredentials('driftApi');
|
|
|
|
|
|
|
|
if (credentials === undefined) {
|
|
|
|
throw new Error('No credentials got returned!');
|
|
|
|
}
|
|
|
|
|
|
|
|
options.headers!['Authorization'] = `Bearer ${credentials.accessToken}`;
|
|
|
|
|
|
|
|
return await this.helpers.request!(options);
|
|
|
|
} else {
|
|
|
|
return await this.helpers.requestOAuth2!.call(this, 'driftOAuth2Api', options);
|
|
|
|
}
|
2020-02-28 16:55:14 -08:00
|
|
|
} catch (error) {
|
2020-06-25 19:29:04 -07:00
|
|
|
|
|
|
|
if (error.response && error.response.body && error.response.body.error) {
|
|
|
|
const errorMessage = error.response.body.error.message;
|
2020-02-28 16:55:14 -08:00
|
|
|
throw new Error(`Drift error response [${error.statusCode}]: ${errorMessage}`);
|
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|