-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdelete-stale-workflow.ts
More file actions
75 lines (60 loc) · 2.01 KB
/
delete-stale-workflow.ts
File metadata and controls
75 lines (60 loc) · 2.01 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
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
type Params = Record<string, never>;
type Env = {
INTEGRATION_TOKEN: string;
};
type Project = {
id: string;
name: string;
createdAt: string;
};
type ProjectsResponse = {
data: Project[];
pagination: {
nextCursor: string | null;
hasMore: boolean;
};
};
export class DeleteStaleProjectsWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep): Promise<void> {
const res = await step.do('fetch-projects', async () => {
const response = await fetch('https://api.prisma.io/v1/projects?limit=1000', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.env.INTEGRATION_TOKEN}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch projects: ${response.statusText}`);
}
const data = await response.text();
return data;
});
const projects: ProjectsResponse = JSON.parse(res);
const now = Date.now();
const twentyFourHours = 24 * 60 * 60 * 1000;
const staleProjects = projects.data.filter((project) => {
const createdAt = new Date(project.createdAt).getTime();
return now - createdAt > twentyFourHours;
});
console.log(`Total projects: ${projects.data.length}, Stale projects: ${staleProjects.length}`);
for (const project of staleProjects) {
await step.do(`delete-project-${project.id}`, async () => {
const deleteRes = await fetch(`https://api.prisma.io/v1/projects/${project.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.env.INTEGRATION_TOKEN}`,
},
});
if (!deleteRes.ok) {
throw new Error(`Failed to delete project ${project.id}: ${deleteRes.statusText}`);
}
console.log(`Deleted stale project: ${project.id} (${project.name})`);
});
}
console.log(`Finished deleting ${staleProjects.length} stale projects`);
}
}
export default DeleteStaleProjectsWorkflow;