-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeleteSchedules.ts
More file actions
142 lines (123 loc) · 4.37 KB
/
deleteSchedules.ts
File metadata and controls
142 lines (123 loc) · 4.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import {getCliClient} from '@sanity/cli'
interface SanityDocument {
documentId: string;
documentType: string;
}
interface SanitySchedule {
id: string;
createdAt: string;
executeAt: string;
executedAt: string;
state: string;
documents: SanityDocument[];
}
interface SchedulesResponse {
schedules: SanitySchedule[];
}
// Parse command line arguments
const args = process.argv.slice(2);
const dryRun = args.find((arg: string) => arg.startsWith('--dry-run='))
? args.find((arg: string) => arg.startsWith('--dry-run='))!.split('=')[1] !== 'false'
: true; // Default to dry-run mode if not specified
const days = args.find((arg: string) => arg.startsWith('--days='))
? parseInt(args.find((arg: string) => arg.startsWith('--days='))!.split('=')[1])
: 90;
const state = args.find((arg: string) => arg.startsWith('--state='))
? args.find((arg: string) => arg.startsWith('--state='))!.split('=')[1]
: 'succeeded';
// Create Sanity client
const client = getCliClient();
const { projectId, dataset } = client.config();
console.log('Configuration loaded:');
console.log('- Project ID:', projectId);
console.log('- Dataset:', dataset);
console.log('- Dry run mode:', dryRun ? 'enabled (will not delete)' : 'disabled (will delete)');
console.log('- State filter:', state);
async function fetchCompletedSchedules(): Promise<SanitySchedule[]> {
try {
const data = await client.request<SchedulesResponse>({
url: `/schedules/${projectId}/${dataset}`,
query: {
tag: 'sanity.studio',
state: state,
limit: '1000'
}
});
// Filter schedules older than 90 days based on executedAt
const checkDate = new Date();
checkDate.setDate(checkDate.getDate() - days);
console.log('Fetched Schedules', data.schedules.length);
return data.schedules.filter(schedule => {
const executionDate = new Date(schedule.executedAt);
return executionDate < checkDate;
});
} catch (error) {
console.error('Error fetching completed schedules:', error);
throw error;
}
}
async function deleteSchedule(scheduleId: string): Promise<void> {
if (dryRun) {
console.log(`[DRY RUN] Would delete schedule: ${scheduleId}`);
return;
}
try {
await client.request({
method: 'DELETE',
url: `/schedules/${projectId}/${dataset}/${scheduleId}`
});
console.log(`Successfully deleted schedule: ${scheduleId}`);
} catch (error) {
console.error(`Error deleting schedule ${scheduleId}:`, error);
throw error;
}
}
async function main(): Promise<void> {
try {
console.log('Fetching completed schedules...');
const completedSchedules = await fetchCompletedSchedules();
console.log(`Found ${completedSchedules.length} schedules completed more than ${days} ${days === 1 ? 'day' : 'days'} ago`);
// Log the schedules for inspection
completedSchedules.forEach((schedule) => {
const documents = schedule.documents.map(doc =>
`${doc.documentType} (${doc.documentId})`
).join(', ');
console.log(
`Schedule ID: ${schedule.id}\n` +
` Documents: ${documents}\n` +
` Created: ${schedule.createdAt}\n` +
` Execute At: ${schedule.executeAt}\n` +
` Executed At: ${schedule.executedAt}\n` +
` State: ${schedule.state}\n`
);
});
if (completedSchedules.length === 0) {
console.log('No schedules to delete.');
return;
}
// Delete each schedule
console.log(`\n${dryRun ? '[DRY RUN] ' : ''}Starting deletion of completed schedules...`);
let successCount = 0;
let failureCount = 0;
for (const schedule of completedSchedules) {
try {
await deleteSchedule(schedule.id);
successCount++;
} catch (error) {
failureCount++;
// Continue with other deletions even if one fails
console.error(`Failed to delete schedule ${schedule.id}. Continuing with remaining schedules...`);
}
}
if (dryRun) {
console.log(`\n[DRY RUN] Would have deleted ${completedSchedules.length} schedules`);
console.log('\nTo perform the actual deletion, run:');
console.log('sanity exec dist/deleteSchedules.js --with-user-token -- --dry-run=false');
} else {
console.log(`\nDeletion complete. Successfully deleted: ${successCount}, Failed: ${failureCount}`);
}
} catch (error) {
console.error('Script failed:', error);
}
}
main();