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

81 lines
2.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';
2020-08-17 13:41:05 -07:00
export const filterAndExecuteForEachTask = async function(
this: IExecuteSingleFunctions,
taskCallback: (t: any) => any
) {
const expression = this.getNodeParameter('expression') as string;
const projectId = this.getNodeParameter('project') as number;
// Enable regular expressions
const reg = new RegExp(expression);
const tasks = await todoistApiRequest.call(this, '/tasks', 'GET');
const filteredTasks = tasks.filter(
// Make sure that project will match no matter what the type is. If project was not selected match all projects
(el: any) => (!projectId || el.project_id) && el.content.match(reg)
);
return {
affectedTasks: (
await Promise.all(filteredTasks.map((t: any) => taskCallback(t)))
)
// This makes it more clear and informative. We pass the ID as a convention and content to give the user confirmation that his/her expression works as expected
.map(
(el, i) =>
el || { id: filteredTasks[i].id, content: filteredTasks[i].content }
)
};
};
export async function todoistApiRequest(
this:
| IHookFunctions
| IExecuteFunctions
| IExecuteSingleFunctions
| ILoadOptionsFunctions,
resource: string,
method: string,
body: any = {},
headers?: object
): Promise<any> {
// tslint:disable-line:no-any
2019-11-05 12:56:10 -08:00
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 {
2020-08-17 13:41:05 -07:00
return this.helpers.request!(options);
2019-11-05 07:17:06 -08:00
} catch (error) {
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}