OAuth2: credentials, genericFunctions, UI

This commit is contained in:
Rupenieks
2020-06-10 12:48:21 +02:00
parent 60fa44722d
commit 9983ed6f8f
4 changed files with 108 additions and 9 deletions

View File

@@ -14,19 +14,13 @@ import {
} from 'n8n-workflow';
export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('surveyMonkeyApi');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
const authenticationMethod = this.getNodeParameter('authentication', 0);
const endpoint = 'https://api.surveymonkey.com/v3';
let options: OptionsWithUri = {
headers: {
'Content-Type': 'application/json',
'Authorization': `bearer ${credentials.accessToken}`,
},
method,
body,
@@ -34,6 +28,7 @@ export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookF
uri: uri || `${endpoint}${resource}`,
json: true
};
if (!Object.keys(body).length) {
delete options.body;
}
@@ -41,8 +36,22 @@ export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookF
delete options.qs;
}
options = Object.assign({}, options, option);
try {
return await this.helpers.request!(options);
if ( authenticationMethod === 'accessToken') {
const credentials = this.getCredentials('surveyMonkeyApi');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
// @ts-ignore
options.headers['Authorization'] = `bearer ${credentials.accessToken}`;
return await this.helpers.request!(options);
} else {
return await this.helpers.requestOAuth2?.call(this, 'surveyMonkeyOAuth2Api', options);
}
} catch (error) {
const errorMessage = error.response.body.error.message;
if (errorMessage !== undefined) {