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
/**
* This API integrates with Calendly to fetch personal events for the current week.
* It returns the events as raw JSON.
*
* Note: This requires a Calendly Personal Access Token to be set as an environment variable.
*/
// Server-side code
async function server(request: Request): Promise<Response> {
const calendlyToken = Deno.env.get('CALENDLY_TOKEN');
if (!calendlyToken) {
return new Response(JSON.stringify({ error: 'Calendly token not set' }), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
try {
// First, get the user's URI
const userResponse = await fetch('https://api.calendly.com/users/me', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${calendlyToken}`
}
});
if (!userResponse.ok) {
throw new Error(`Failed to fetch user data: ${userResponse.status} ${userResponse.statusText}`);
}
const userData = await userResponse.json();
const userUri = userData.resource.uri;
// Calculate the start and end of the current week
const today = new Date();
const startOfWeek = new Date(today.setDate(today.getDate() - today.getDay()));
const endOfWeek = new Date(today.setDate(today.getDate() - today.getDay() + 6));
// Now fetch the events using the user's URI
const eventsUrl = `https://api.calendly.com/scheduled_events?user=${userUri}&min_start_time=${startOfWeek.toISOString()}&max_start_time=${endOfWeek.toISOString()}`;
const eventsResponse = await fetch(eventsUrl, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${calendlyToken}`
}
});
if (!eventsResponse.ok) {
throw new Error(`Failed to fetch Calendly events: ${eventsResponse.status} ${eventsResponse.statusText}`);
}
const eventsData = await eventsResponse.json();
const events = eventsData.collection.map((event: any) => ({
name: event.name,
startTime: event.start_time,
endTime: event.end_time,
link: event.uri
}));
events.sort((a: any, b: any) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
return new Response(JSON.stringify(events), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error('Error:', error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
export default server;