n8n/packages/nodes-base/nodes/NextCloud/GenericFunctions.ts

63 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-06-17 10:38:30 -07:00
import {
IExecuteFunctions,
IHookFunctions,
} from 'n8n-core';
import {
JsonObject,
NodeApiError,
} from 'n8n-workflow';
2020-06-17 10:38:30 -07:00
import {
2020-07-22 14:52:40 -07:00
OptionsWithUri,
} from 'request';
2020-06-17 10:38:30 -07:00
/**
* Make an API request to NextCloud
*
* @param {IHookFunctions} this
* @param {string} method
* @param {string} url
* @param {object} body
* @returns {Promise<any>}
*/
export async function nextCloudApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: object | string | Buffer, headers?: object, encoding?: null | undefined, query?: object): Promise<any> { // tslint:disable-line:no-any
2021-01-22 11:58:06 -08:00
const resource = this.getNodeParameter('resource', 0);
const operation = this.getNodeParameter('operation', 0);
const authenticationMethod = this.getNodeParameter('authentication', 0);
let credentials;
if (authenticationMethod === 'accessToken') {
credentials = await this.getCredentials('nextCloudApi') as { webDavUrl: string };
} else {
credentials = await this.getCredentials('nextCloudOAuth2Api') as { webDavUrl: string };
}
let options: OptionsWithUri = {
2020-06-17 10:38:30 -07:00
headers,
method,
body,
qs: query ?? {},
2020-06-17 10:38:30 -07:00
uri: '',
json: false,
};
if (encoding === null) {
options.encoding = null;
}
options.uri = `${credentials.webDavUrl}/${encodeURI(endpoint)}`;
if (resource === 'user' && operation === 'create') {
options.uri = options.uri.replace('/remote.php/webdav', '');
}
2020-06-17 10:38:30 -07:00
const credentialType = authenticationMethod === 'accessToken' ? 'nextCloudApi' : 'nextCloudOAuth2Api';
2021-01-22 11:58:06 -08:00
try {
return await this.helpers.requestWithAuthentication.call(this, credentialType, options);
} catch(error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
2020-06-17 10:38:30 -07:00
}
}