|
| 1 | +import { zValidator } from "@hono/zod-validator"; |
| 2 | +import { Hono } from "hono"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { env } from "hono/adapter"; |
| 5 | + |
| 6 | +// Define the app context type to include environment variables |
| 7 | +interface AppEnv { |
| 8 | + NTHUMODS_AUTH_URL: string; |
| 9 | +} |
| 10 | + |
| 11 | +const app = new Hono<{ Bindings: AppEnv }>() |
| 12 | + .get( |
| 13 | + "/ical/:userId", |
| 14 | + zValidator( |
| 15 | + "query", |
| 16 | + z.object({ |
| 17 | + key: z.string().optional(), |
| 18 | + type: z.enum(["basic", "full"]).default("basic"), |
| 19 | + }), |
| 20 | + ), |
| 21 | + zValidator( |
| 22 | + "param", |
| 23 | + z.object({ |
| 24 | + userId: z.string(), |
| 25 | + }), |
| 26 | + ), |
| 27 | + async (c) => { |
| 28 | + try { |
| 29 | + const { userId } = c.req.valid("param"); |
| 30 | + const { key, type } = c.req.valid("query"); |
| 31 | + |
| 32 | + if (!key) { |
| 33 | + return c.json({ error: "Missing API key" }, 400); |
| 34 | + } |
| 35 | + |
| 36 | + // Get the secure API URL from environment variable |
| 37 | + const { NTHUMODS_AUTH_URL: secureApiUrl } = env<{ NTHUMODS_AUTH_URL: string }>(c); |
| 38 | + |
| 39 | + // Construct the URL for the secure API request |
| 40 | + const url = new URL(`${secureApiUrl}/calendar/ics/${userId}`); |
| 41 | + url.searchParams.set("key", key); |
| 42 | + url.searchParams.set("type", type); |
| 43 | + |
| 44 | + // Forward the request to the secure API |
| 45 | + const response = await fetch(url.toString(), { |
| 46 | + headers: { |
| 47 | + // Forward any necessary headers |
| 48 | + "Accept": "text/calendar", |
| 49 | + }, |
| 50 | + }); |
| 51 | + |
| 52 | + // Check if the request was successful |
| 53 | + if (!response.ok) { |
| 54 | + const errorText = await response.text(); |
| 55 | + console.error(`Error fetching calendar: ${response.status} ${errorText}`); |
| 56 | + return c.json( |
| 57 | + { error: `Failed to fetch calendar: ${response.statusText}`, status: response.status } |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + // Get the calendar data |
| 62 | + const calendarData = await response.text(); |
| 63 | + |
| 64 | + // Set the appropriate headers for the iCalendar file |
| 65 | + c.header("Content-Type", "text/calendar"); |
| 66 | + c.header("Content-Disposition", `attachment; filename=${userId}_calendar.ics`); |
| 67 | + c.header("Cache-Control", "private, max-age=3600"); // Cache for 1 hour |
| 68 | + |
| 69 | + // Return the calendar data |
| 70 | + return c.body(calendarData); |
| 71 | + } catch (error) { |
| 72 | + console.error("Error proxying calendar request:", error); |
| 73 | + return c.json( |
| 74 | + { error: "Internal server error while fetching calendar" }, |
| 75 | + 500 |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | + ); |
| 80 | + |
| 81 | +export default app; |
0 commit comments