n8n/packages/nodes-base/nodes/Todoist/Todoist.node.ts
Gonçalo Silva dc77594a1e
feat(Todoist Node): Add support for specifying the parent task when adding and listing tasks (#3161)
* Todoist: Update parent field to parent_id

`parent` is deprecated.

* Todoist: Move Labels to "additional fields" when adding a task

Improves consistency with other operations.

* Todoist: Improve section re-load when switching projects

It only worked when creating tasks, due to naming and nesting
inconsistencies between different operations. Making it consistent
adds predictability and allows reuse between operations.

* Todoist: Add support for parent_id when creating and listing tasks

*  fixes

*  test credentials fix

*  parameters naming fix

*  undo for breaking change

* feat(Salesforce Node): Add country field (#3314)

* fix(Slack Node): Fix Channel->Kick (#3365)

* feat(core): Allow credential reuse on HTTP Request node (#3228)

*  Create controller

*  Mount controller

* ✏️ Add error messages

*  Create scopes fetcher

*  Account for non-existent credential type

* 📘 Type scopes request

*  Adjust error message

* 🧪 Add tests

*  Introduce simple node versioning

*  Add example how to read version in node-code for custom logic

* 🐛 Fix setting of parameters

* 🐛 Fix another instance where it sets the wrong parameter

*  Remove unnecessary TOODs

*  Re-version HTTP Request node

* 👕 Satisfy linter

*  Retrieve node version

*  Undo Jan's changes to Set node

* 🧪 Fix CI/CD for `/oauth2-credential` tests (#3230)

* 🐛 Fix notice warning missing background color (#3231)

* 🐛 Check for generic auth in node cred types

*  Refactor credentials dropdown for HTTP Request node (#3222)

*  Discoverability flow (#3229)

*  Added node credentials type proxy. Changed node credentials input order.

*  Add computed property from versioning branch

* 🐛 Fix cred ref lost and unsaved

*  Make options consistent with cred type names

*  Use prop to set component order

*  Use constant and version

*  Fix rendering for generic auth creds

*  Mark as required on first selection

*  Implement discoverability flow

*  Mark as required on subsequent selections

*  Fix marking as required after cred deletion

*  Refactor to clean up

*  Detect position automatically

*  Add i18n to option label

*  Hide subtitle for custom action

*  Detect active credential type

*  Prop drilling to re-render select

* 🔥 Remove unneeded property

* ✏️ Rename arg

* 🔥 Remove unused import

* 🔥 Remove unneeded getters

* 🔥 Remove unused import

*  Generalize cred component positioning

*  Set up request

* 🐛 Fix edge case in endpoint

*  Display scopes alert box

*  Revert "Generalize cred comp positioning"

This reverts commit 75eea89273.

*  Consolidate HTTPRN check

*  Fix hue percentage to degree

* 🔥 Remove unused import

* 🔥 Remove unused import

* 🔥 Remove unused class

* 🔥 Remove unused import

* 📘 Create type for HTTPRN v2 auth params

* ✏️ Rename check

* 🔥 Remove unused import

* ✏️ Add i18n to `reportUnsetCredential()`

*  Refactor Alex's spacing changes

*  Post-merge fixes

*  Add docs link

* 🔥 Exclude Notion OAuth cred

* ✏️ Update copy

* ✏️ Rename param

* 🎨 Reposition notice and simplify styling

* ✏️ Update copy

* ✏️ Update copy

*  Hide params during custom action

*  Show notice if any cred type supported

* 🐛 Prevent scopes text overflow

* 🔥 Remove superfluous check

* ✏️ Break up docstring

* 🎨 Tweak notice styling

*  Reorder cred param in Webhook node

* ✏️ Shorten cred name in scopes notice

* 🧪 Update Notice snapshots

* 🐛 Fix check when `globalRole` is `undefined`

*  Revert 3f2c4a6

*  Apply feedback from Product

* 🧪 Update snapshot

*  Adjust regex expansion pattern for singular

* 🔥 Remove unused import

* 🔥 Remove logging

*  Make `somethingElse` key more unique

*  Move something else to constants

*  Consolidate notice component

*  Apply latest feedback

* 🧪 Update tests

* 🧪 Update snapshot

* ✏️ Fix singular version

* 🧪 Finalize tests

* ✏️ Rename constant

* 🧪 Expand tests

* 🔥 Remove `truncate` prop

* 🚚 Move scopes fetching to store

* 🚚 Move method to component

*  Use constant

*  Refactor `Notice` component

* 🧪 Update tests

* 🔥 Remove unused keys

*  Inject custom API call option

* 🔥 Remove unused props

* 🎨 Use `compact` prop

* 🧪 Update snapshots

* 🚚 Move scopes to store

* 🚚 Move `nodeCredentialTypes` to parent

* ✏️ Rename cred types per branding

* 🐛 Clear scopes when none

*  Add default

* 🚚 Move `newHttpRequestNodeCredentialType` to parent

* 🔥 Remove test data

*  Separate lines for readability

*  Change reference from node to node name

* ✏️ Rename i18n keys

*  Refactor OAuth check

* 🔥 Remove unused key

* 🚚 Move `OAuth1/2 API` to i18n

*  Refactor `skipCheck`

*  Add `stopPropagation` and `preventDefault`

* 🚚 Move active credential scopes logic to store

* 🎨 Fix spacing for `NodeWebhooks` component

*  Implement feedback

*  Update HTTPRN default and issue copy

* Refactor to use `CredentialsSelect` param (#3304)

*  Refactor into cred type param

*  Componentize scopes notice

* 🔥 Remove unused data

* 🔥 Remove unused `loadOptions`

*  Componentize `NodeCredentialType`

* 🐛 Fix param validation

* 🔥 Remove dup methods

*  Refactor all references to `isHttpRequestNodeV2`

* 🎨 Fix styling

* 🔥 Remove unused import

* 🔥 Remove unused properties

* 🎨 Fix spacing for Pipedrive Trigger node

* 🎨 Undo Webhook node styling change

* 🔥 Remove unused style

*  Cover `httpHeaderAuth` edge case

* 🐛 Fix `this.node` reference

* 🚚 Rename to `credentialsSelect`

* 🐛 Fix mistaken renaming

*  Set one attribute per line

*  Move condition to instantiation site

* 🚚 Rename prop

*  Refactor away `prepareScopesNotice`

* ✏️ Rename i18n keys

* ✏️ Update i18n calls

* ✏️ Add more i18n keys

* 🔥 Remove unused props

* ✏️ Add explanatory comment

*  Adjust check in `hasProxyAuth`

*  Refactor `credentialSelected` from prop to event

*  Eventify `valueChanged`, `setFocus`, `onBlur`

*  Eventify `optionSelected`

*  Add `noDataExpression`

* 🔥 Remove logging

* 🔥 Remove URL from scopes

*  Disregard expressions for display

* 🎨 Use CSS modules

* 📘 Tigthen interface

* 🐛 Fix generic auth display

* 🐛 Fix generic auth validation

* 📘 Loosen type

* 🚚 Move event params to end

*  Generalize reference

*  Refactor generic auth as `credentialsSelect` param

*  Restore check for `httpHeaderAuth `

* 🚚 Rename `existing` to `predefined`

* Extend metrics for HTTP Request node (#3282)

*  Extend metrics

* 🧪 Add tests

*  Update param names

Co-authored-by: Alex Grozav <alex@grozav.com>

*  Update check per new branch

*  Include generic auth check

*  Adjust telemetry (#3359)

*  Filter credential types by label

Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
Co-authored-by: Alex Grozav <alex@grozav.com>

* ⬆️ Update package-lock.json file

* 🔖 Release n8n-workflow@0.100.0

* ⬆️ Set n8n-workflow@0.100.0 on n8n-core

* 🔖 Release n8n-core@0.118.0

* ⬆️ Set n8n-core@0.118.0 and n8n-workflow@0.100.0 on n8n-node-dev

* 🔖 Release n8n-node-dev@0.57.0

* ⬆️ Set n8n-core@0.118.0 and n8n-workflow@0.100.0 on n8n-nodes-base

* 🔖 Release n8n-nodes-base@0.176.0

* 🔖 Release n8n-design-system@0.21.0

* ⬆️ Set n8n-design-system@0.21.0 and n8n-workflow@0.100.0 on n8n-editor-ui

* 🔖 Release n8n-editor-ui@0.144.0

* ⬆️ Set n8n-core@0.118.0, n8n-editor-ui@0.144.0, n8n-nodes-base@0.176.0 and n8n-workflow@0.100.0 on n8n

* 🔖 Release n8n@0.178.0

* 🔖 Update main package.json to 0.178.0

* 📚 Update CHANGELOG.md with version 0.178.0

* fix(editor): Fix problem with HTTP Request Node 1 credentials to be set (#3371)

* 🔖 Release n8n-editor-ui@0.144.1

* ⬆️ Set n8n-editor-ui@0.144.1 on n8n

* 🔖 Release n8n@0.178.1

* 🔖 Update main package.json to 0.178.1

* 📚 Update CHANGELOG.md with version 0.178.1

* fix(editor): Fix parameter loading bug (#3374)

* fix parameter loading bug

* remove duplicate check

* 🔖 Release n8n-editor-ui@0.144.2

* ⬆️ Set n8n-editor-ui@0.144.2 on n8n

* 🔖 Release n8n@0.178.2

* 🔖 Update main package.json to 0.178.2

* 📚 Update CHANGELOG.md with version 0.178.2

*  Improvements

* fix(core): Fix issue that "closeFunction" got called twice

* fix(core): Prevent expressions XSS (#3366)

*  Added checks for window object access in template strings.

*  Added self, prompt and confirm to blocklist. Changed window usage condition.

* fix(editor): Fix conflicting hover states between sticky button and node view (#3368)

* 🐛 Fixing conflicting hover states between sticky button and node view.

* 🔨 Updating and optimizing sticky menu hover logic

* 📇 Removing redundant comments from `NodeView`.

* fix(editor): Fix credential display bug (#3372)

*  Filter credentials by version

*  Reuse helper

* fix(NextCloud Node): Fix folder list with Nextcloud v24 (#3386)

* initial fix for v24 folder listing

* implemented new credential methods

* Nodelinter fixes

* feat(PostBin Node): Add PostBin node  (#3236)

* 🚧 Initial progress on PostBin node.

*  Implemented Bin and Request operations for PostBin node.

* 🚧 Reworked the node in the declarative way.

* 🚧 PosBin node refactoring after reworking it.

*  Implemented Bin id parsing in PostBin node. Done some final refactoring and documentation.

*  Improvements

*  Add comments

* 👌Updating the PostBin node based on the product review

* 💄Updating PostBin node Bin ID validation logic

*  Small improvements

*  Transform the bin requests and add additional properties

Co-authored-by: ricardo <ricardoespinoza105@gmail.com>
Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>

*  Simplify auth

* 👕 Fix lint issue

Co-authored-by: Michael Kret <michael.k@radency.com>
Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com>
Co-authored-by: Jan Oberhauser <janober@users.noreply.github.com>
Co-authored-by: Iván Ovejero <ivov.src@gmail.com>
Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
Co-authored-by: Alex Grozav <alex@grozav.com>
Co-authored-by: Mutasem Aldmour <4711238+mutdmour@users.noreply.github.com>
Co-authored-by: ricardo <ricardoespinoza105@gmail.com>
Co-authored-by: Milorad FIlipović <miloradfilipovic19@gmail.com>
Co-authored-by: Jonathan Bennetts <jonathan.bennetts@gmail.com>
2022-05-27 18:15:05 +02:00

814 lines
19 KiB
TypeScript

import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import {
FormatDueDatetime,
todoistApiRequest,
} from './GenericFunctions';
interface IBodyCreateTask {
content?: string;
description?: string;
project_id?: number;
section_id?: number;
parent_id?: number;
order?: number;
label_ids?: number[];
priority?: number;
due_string?: string;
due_datetime?: string;
due_date?: string;
due_lang?: string;
}
export class Todoist implements INodeType {
description: INodeTypeDescription = {
displayName: 'Todoist',
name: 'todoist',
icon: 'file:todoist.svg',
group: ['output'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Todoist API',
defaults: {
name: 'Todoist',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'todoistApi',
required: true,
displayOptions: {
show: {
authentication: [
'apiKey',
],
},
},
},
{
name: 'todoistOAuth2Api',
required: true,
displayOptions: {
show: {
authentication: [
'oAuth2',
],
},
},
},
],
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'API Key',
value: 'apiKey',
},
{
name: 'OAuth2',
value: 'oAuth2',
},
],
default: 'apiKey',
},
{
displayName: 'Resource',
name: 'resource',
type: 'options',
noDataExpression: true,
options: [
{
name: 'Task',
value: 'task',
description: 'Task resource',
},
],
default: 'task',
required: true,
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
required: true,
displayOptions: {
show: {
resource: [
'task',
],
},
},
options: [
{
name: 'Close',
value: 'close',
description: 'Close a task',
},
{
name: 'Create',
value: 'create',
description: 'Create a new task',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a task',
},
{
name: 'Get',
value: 'get',
description: 'Get a task',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all tasks',
},
{
name: 'Reopen',
value: 'reopen',
description: 'Reopen a task',
},
{
name: 'Update',
value: 'update',
description: 'Update a task',
},
],
default: 'create',
},
{
displayName: 'Project',
name: 'project',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getProjects',
},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'create',
],
},
},
default: '',
description: 'The project you want to operate on',
},
{
displayName: 'Labels',
name: 'labels',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'create',
],
},
},
default: [],
description: 'Optional labels that will be assigned to a created task',
},
{
displayName: 'Content',
name: 'content',
type: 'string',
typeOptions: {
rows: 5,
},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'create',
],
},
},
default: '',
required: true,
description: 'Task content',
},
{
displayName: 'Task ID',
name: 'taskId',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'delete',
'close',
'get',
'reopen',
'update',
],
},
},
},
{
displayName: 'Additional Fields',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'create',
],
},
},
options: [
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: 'A description for the task',
},
{
displayName: 'Due Date Time',
name: 'dueDateTime',
type: 'dateTime',
default: '',
description: 'Specific date and time in RFC3339 format in UTC',
},
{
displayName: 'Due String Locale',
name: 'dueLang',
type: 'string',
default: '',
description: '2-letter code specifying language in case due_string is not written in English',
},
{
displayName: 'Due String',
name: 'dueString',
type: 'string',
default: '',
description: 'Human defined task due date (ex.: “next Monday”, “Tomorrow”). Value is set using local (not UTC) time.',
},
{
displayName: 'Parent ID',
name: 'parentId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getItems',
loadOptionsDependsOn: [
'project',
'options.section',
],
},
default: {},
description: 'The parent task you want to operate on',
},
{
displayName: 'Priority',
name: 'priority',
type: 'number',
typeOptions: {
maxValue: 4,
minValue: 1,
},
default: 1,
description: 'Task priority from 1 (normal) to 4 (urgent)',
},
{
displayName: 'Section ID',
name: 'section',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getSections',
loadOptionsDependsOn: [
'project',
],
},
default: {},
description: 'The section you want to operate on',
},
],
},
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'task',
],
},
},
default: false,
description: 'Whether to return all results or only up to a given limit',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'task',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 50,
description: 'Max number of results to return',
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'getAll',
],
},
},
options: [
{
displayName: 'Filter',
name: 'filter',
type: 'string',
default: '',
description: 'Filter by any <a href="https://get.todoist.help/hc/en-us/articles/205248842">supported filter.</a>',
},
{
displayName: 'IDs',
name: 'ids',
type: 'string',
default: '',
description: 'A list of the task IDs to retrieve, this should be a comma-separated list',
},
{
displayName: 'Label ID',
name: 'labelId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: {},
description: 'Filter tasks by label',
},
{
displayName: 'Lang',
name: 'lang',
type: 'string',
default: '',
description: 'IETF language tag defining what language filter is written in, if differs from default English',
},
{
displayName: 'Parent ID',
name: 'parentId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getItems',
loadOptionsDependsOn: [
'filters.projectId',
'filters.sectionId',
],
},
default: '',
description: 'Filter tasks by parent task ID',
},
{
displayName: 'Project ID',
name: 'projectId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getProjects',
},
default: '',
description: 'Filter tasks by project ID',
},
{
displayName: 'Section ID',
name: 'sectionId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getSections',
loadOptionsDependsOn: [
'filters.projectId',
],
},
default: '',
description: 'Filter tasks by section ID',
},
],
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'task',
],
operation: [
'update',
],
},
},
options: [
{
displayName: 'Content',
name: 'content',
type: 'string',
default: '',
description: 'Task content',
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: 'A description for the task',
},
{
displayName: 'Due Date Time',
name: 'dueDateTime',
type: 'dateTime',
default: '',
description: 'Specific date and time in RFC3339 format in UTC',
},
{
displayName: 'Due String Locale',
name: 'dueLang',
type: 'string',
default: '',
description: '2-letter code specifying language in case due_string is not written in English',
},
{
displayName: 'Due String',
name: 'dueString',
type: 'string',
default: '',
description: 'Human defined task due date (ex.: “next Monday”, “Tomorrow”). Value is set using local (not UTC) time.',
},
{
displayName: 'Labels',
name: 'labels',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
},
{
displayName: 'Priority',
name: 'priority',
type: 'number',
typeOptions: {
maxValue: 4,
minValue: 1,
},
default: 1,
description: 'Task priority from 1 (normal) to 4 (urgent)',
},
],
},
],
};
methods = {
loadOptions: {
// Get all the available projects to display them to user so that he can
// select them easily
async getProjects(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const projects = await todoistApiRequest.call(this, 'GET', '/projects');
for (const project of projects) {
const projectName = project.name;
const projectId = project.id;
returnData.push({
name: projectName,
value: projectId,
});
}
return returnData;
},
// Get all the available sections in the selected project, to display them
// to user so that he can select one easily
async getSections(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const options = Object.assign({},
this.getNodeParameter('options', {}),
this.getNodeParameter('filters', {}),
) as IDataObject;
const projectId = options.projectId as number ??
this.getCurrentNodeParameter('project') as number;
if (projectId) {
const qs: IDataObject = {project_id: projectId};
const sections = await todoistApiRequest.call(this, 'GET', '/sections', {}, qs);
for (const section of sections) {
const sectionName = section.name;
const sectionId = section.id;
returnData.push({
name: sectionName,
value: sectionId,
});
}
}
return returnData;
},
// Get all the available parents in the selected project and section,
// to display them to user so that they can select one easily
async getItems(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const options = Object.assign({},
this.getNodeParameter('options', {}),
this.getNodeParameter('filters', {}),
) as IDataObject;
const projectId = options.projectId as number ??
this.getCurrentNodeParameter('project') as number;
const sectionId = options.sectionId as number || options.section as number ||
this.getCurrentNodeParameter('sectionId') as number;
if (projectId) {
const qs: IDataObject = sectionId ?
{project_id: projectId, section_id: sectionId} : {project_id: projectId};
const items = await todoistApiRequest.call(this, 'GET', '/tasks', {}, qs);
for (const item of items) {
const itemContent = item.content;
const itemId = item.id;
returnData.push({
name: itemContent,
value: itemId,
});
}
}
return returnData;
},
// Get all the available labels to display them to user so that he can
// select them easily
async getLabels(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const labels = await todoistApiRequest.call(this, 'GET', '/labels');
for (const label of labels) {
const labelName = label.name;
const labelId = label.id;
returnData.push({
name: labelName,
value: labelId,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = items.length;
const qs: IDataObject = {};
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
try {
if (resource === 'task') {
if (operation === 'create') {
//https://developer.todoist.com/rest/v1/#create-a-new-task
const content = this.getNodeParameter('content', i) as string;
const projectId = this.getNodeParameter('project', i) as number;
const labels = this.getNodeParameter('labels', i) as number[];
const options = this.getNodeParameter('options', i) as IDataObject;
const body: IBodyCreateTask = {
content,
project_id: projectId,
priority: (options.priority!) ? parseInt(options.priority as string, 10) : 1,
};
if (options.description) {
body.description = options.description as string;
}
if (options.dueDateTime) {
body.due_datetime = FormatDueDatetime(options.dueDateTime as string);
}
if (options.dueString) {
body.due_string = options.dueString as string;
}
if (options.dueLang) {
body.due_lang = options.dueLang as string;
}
if (labels !== undefined && labels.length !== 0) {
body.label_ids = labels as number[];
}
if (options.section) {
body.section_id = options.section as number;
}
if (options.parentId) {
body.parent_id = options.parentId as number;
}
responseData = await todoistApiRequest.call(this, 'POST', '/tasks', body);
}
if (operation === 'close') {
//https://developer.todoist.com/rest/v1/#close-a-task
const id = this.getNodeParameter('taskId', i) as string;
responseData = await todoistApiRequest.call(this, 'POST', `/tasks/${id}/close`);
responseData = { success: true };
}
if (operation === 'delete') {
//https://developer.todoist.com/rest/v1/#delete-a-task
const id = this.getNodeParameter('taskId', i) as string;
responseData = await todoistApiRequest.call(this, 'DELETE', `/tasks/${id}`);
responseData = { success: true };
}
if (operation === 'get') {
//https://developer.todoist.com/rest/v1/#get-an-active-task
const id = this.getNodeParameter('taskId', i) as string;
responseData = await todoistApiRequest.call(this, 'GET', `/tasks/${id}`);
}
if (operation === 'getAll') {
//https://developer.todoist.com/rest/v1/#get-active-tasks
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i, {}) as IDataObject;
if (filters.projectId) {
qs.project_id = filters.projectId as string;
}
if (filters.sectionId) {
qs.section_id = filters.sectionId as string;
}
if (filters.parentId) {
qs.parent_id = filters.parentId as string;
}
if (filters.labelId) {
qs.label_id = filters.labelId as string;
}
if (filters.filter) {
qs.filter = filters.filter as string;
}
if (filters.lang) {
qs.lang = filters.lang as string;
}
if (filters.ids) {
qs.ids = filters.ids as string;
}
responseData = await todoistApiRequest.call(this, 'GET', '/tasks', {}, qs);
if (!returnAll) {
const limit = this.getNodeParameter('limit', i) as number;
responseData = responseData.splice(0, limit);
}
}
if (operation === 'reopen') {
//https://developer.todoist.com/rest/v1/#get-an-active-task
const id = this.getNodeParameter('taskId', i) as string;
responseData = await todoistApiRequest.call(this, 'POST', `/tasks/${id}/reopen`);
responseData = { success: true };
}
if (operation === 'update') {
//https://developer.todoist.com/rest/v1/#update-a-task
const id = this.getNodeParameter('taskId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IBodyCreateTask = {};
if (updateFields.content) {
body.content = updateFields.content as string;
}
if (updateFields.priority) {
body.priority = parseInt(updateFields.priority as string, 10);
}
if (updateFields.description) {
body.description = updateFields.description as string;
}
if (updateFields.dueDateTime) {
body.due_datetime = FormatDueDatetime(updateFields.dueDateTime as string);
}
if (updateFields.dueString) {
body.due_string = updateFields.dueString as string;
}
if (updateFields.dueLang) {
body.due_lang = updateFields.dueLang as string;
}
if (updateFields.labels !== undefined &&
Array.isArray(updateFields.labels) &&
updateFields.labels.length !== 0) {
body.label_ids = updateFields.labels as number[];
}
await todoistApiRequest.call(this, 'POST', `/tasks/${id}`, body);
responseData = { success: true };
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData as IDataObject);
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}