2020-07-23 18:08:34 -07:00
|
|
|
import {
|
|
|
|
IExecuteFunctions,
|
|
|
|
IHookFunctions,
|
|
|
|
} from 'n8n-core';
|
|
|
|
|
|
|
|
import {
|
|
|
|
OptionsWithUri,
|
|
|
|
} from 'request';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IDataObject,
|
|
|
|
} from 'n8n-workflow';
|
2020-06-03 07:24:17 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Make an API request to Dropbox
|
|
|
|
*
|
|
|
|
* @param {IHookFunctions} this
|
|
|
|
* @param {string} method
|
|
|
|
* @param {string} url
|
|
|
|
* @param {object} body
|
|
|
|
* @returns {Promise<any>}
|
|
|
|
*/
|
2020-07-23 18:20:21 -07:00
|
|
|
export async function dropboxApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: object, query: IDataObject = {}, headers?: object, option: IDataObject = {}): Promise<any> {// tslint:disable-line:no-any
|
2020-06-03 07:24:17 -07:00
|
|
|
|
|
|
|
const options: OptionsWithUri = {
|
|
|
|
headers,
|
|
|
|
method,
|
2020-07-23 18:20:21 -07:00
|
|
|
qs: query,
|
2020-06-03 07:24:17 -07:00
|
|
|
body,
|
|
|
|
uri: endpoint,
|
|
|
|
json: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!Object.keys(body).length) {
|
|
|
|
delete options.body;
|
|
|
|
}
|
|
|
|
|
2020-07-23 18:08:34 -07:00
|
|
|
Object.assign(options, option);
|
2020-06-04 08:16:33 -07:00
|
|
|
|
|
|
|
const authenticationMethod = this.getNodeParameter('authentication', 0) as string;
|
|
|
|
|
2020-06-03 07:24:17 -07:00
|
|
|
try {
|
|
|
|
if (authenticationMethod === 'accessToken') {
|
2020-07-23 18:08:34 -07:00
|
|
|
|
|
|
|
const credentials = this.getCredentials('dropboxApi') as IDataObject;
|
|
|
|
|
|
|
|
options.headers!['Authorization'] = `Bearer ${credentials.accessToken}`;
|
|
|
|
|
2020-06-03 07:24:17 -07:00
|
|
|
return await this.helpers.request(options);
|
|
|
|
} else {
|
2020-06-25 20:37:26 -07:00
|
|
|
return await this.helpers.requestOAuth2.call(this, 'dropboxOAuth2Api', options);
|
2020-06-03 07:24:17 -07:00
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
if (error.statusCode === 401) {
|
|
|
|
// Return a clear error
|
|
|
|
throw new Error('The Dropbox credentials are not valid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error.error && error.error.error_summary) {
|
|
|
|
// Try to return the error prettier
|
|
|
|
throw new Error(
|
2020-10-22 09:00:28 -07:00
|
|
|
`Dropbox error response [${error.statusCode}]: ${error.error.error_summary}`,
|
2020-06-03 07:24:17 -07:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// If that data does not exist for some reason return the actual error
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|