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

64 lines
1.3 KiB
TypeScript
Raw Normal View History

import {
OptionsWithUri,
} from 'request';
2019-11-05 07:17:06 -08:00
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
import {
IDataObject,
} from 'n8n-workflow';
2020-08-17 13:41:05 -07:00
export async function todoistApiRequest(
this:
| IHookFunctions
| IExecuteFunctions
| ILoadOptionsFunctions,
method: string,
resource: string,
body: any = {}, // tslint:disable-line:no-any
qs: IDataObject = {},
): Promise<any> { // tslint:disable-line:no-any
const authentication = this.getNodeParameter('authentication', 0, 'apiKey');
2019-11-05 07:17:06 -08:00
2019-11-05 12:56:10 -08:00
const endpoint = 'api.todoist.com/rest/v1';
2019-11-05 07:17:06 -08:00
const options: OptionsWithUri = {
headers: {},
2019-11-05 07:17:06 -08:00
method,
qs,
2019-11-05 12:56:10 -08:00
uri: `https://${endpoint}${resource}`,
json: true,
2019-11-05 07:17:06 -08:00
};
if (Object.keys(body).length !== 0) {
options.body = body;
2019-11-05 12:56:10 -08:00
}
2019-11-05 07:17:06 -08:00
try {
if (authentication === 'apiKey') {
const credentials = this.getCredentials('todoistApi') as IDataObject;
//@ts-ignore
options.headers['Authorization'] = `Bearer ${credentials.apiKey}`;
return this.helpers.request!(options);
} else {
//@ts-ignore
return await this.helpers.requestOAuth2.call(this, 'todoistOAuth2Api', options);
}
2019-11-05 07:17:06 -08:00
} catch (error) {
const errorMessage = error.response.body;
2019-11-05 07:17:06 -08:00
if (errorMessage !== undefined) {
throw new Error(errorMessage);
2019-11-05 07:17:06 -08:00
}
throw errorMessage;
2019-11-05 07:17:06 -08:00
}
}