0

Create Filter

by
Published Jun 6, 2022

Creates a filter. [See the docs here](https://developer.todoist.com/sync/v9/#add-a-filter)

Script todoist Verified

The script

Submitted by hugo697 Bun
Verified 398 days ago
1
import { v9 as Todoist } from 'todoist'
2
import { v4 as uuidv4 } from 'uuid'
3

4
type Todoist = {
5
	Token: string
6
}
7

8
interface Response {
9
	full_sync: boolean
10
	sync_status: Sync_status
11
	sync_token: string
12
	temp_id_mapping: Temp_id_mapping
13
}
14
interface Sync_status {
15
	[key: string]: string
16
}
17
interface Temp_id_mapping {
18
	[key: string]: string
19
}
20

21
export async function main(
22
	resource: Todoist,
23
	filter: {
24
		name: string
25
		query: string
26
		color?:
27
			| 'berry_red'
28
			| 'red'
29
			| 'orange'
30
			| 'yellow'
31
			| 'olive_green'
32
			| 'lime_green'
33
			| 'green'
34
			| 'mint_green'
35
			| 'teal'
36
			| 'sky_blue'
37
			| 'light_blue'
38
			| 'blue'
39
			| 'grape'
40
			| 'violet'
41
			| 'lavender'
42
			| 'magenta'
43
			| 'salmon'
44
			| 'charcoal'
45
			| 'grey'
46
			| 'taupe'
47
		item_order?: number
48
		is_favorite?: boolean
49
	}
50
) {
51
	const response = await fetch('https://api.todoist.com/sync/v9/sync', {
52
		method: 'POST',
53
		headers: {
54
			Authorization: `Bearer ${resource.Token}`,
55
			'Content-Type': 'application/json'
56
		},
57
		body: JSON.stringify({
58
			commands: [
59
				{
60
					type: 'filter_add',
61
					temp_id: uuidv4(),
62
					uuid: uuidv4(),
63
					args: {
64
						name: filter.name,
65
						query: filter.query,
66
						color: filter.color,
67
						item_order: filter.item_order,
68
						is_favorite: filter.is_favorite
69
					}
70
				}
71
			]
72
		})
73
	})
74
	if (!response.ok) {
75
		throw new Error(`HTTP error! status: ${response.status}`)
76
	}
77
	const data = (await response.json()) as Response
78
	const tempId = Object.keys(data.temp_id_mapping)[0]
79
	const createdFilterId = data.temp_id_mapping[tempId]
80
	return {
81
		id: createdFilterId
82
	}
83
}
84