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

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2019-11-05 07:17:06 -08:00
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
IExecuteSingleFunctions
} from 'n8n-core';
import * as _ from 'lodash';
2019-11-05 12:56:10 -08:00
export async function todoistApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, resource: string, method: string, body: any = {}, headers?: object): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('todoistApi');
2019-11-05 07:17:06 -08:00
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
2019-11-05 12:56:10 -08:00
const headerWithAuthentication = Object.assign({}, headers, { Authorization: `Bearer ${credentials.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 = {
2019-11-05 12:56:10 -08:00
headers: headerWithAuthentication,
2019-11-05 07:17:06 -08:00
method,
2019-11-05 12:56:10 -08:00
uri: `https://${endpoint}${resource}`,
2019-11-05 07:17:06 -08:00
json: true
};
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 {
return await this.helpers.request!(options);
} catch (error) {
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}