route.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { listFiles } from "@/lib/storage";
  2. import { getSession } from "@/lib/auth/session";
  3. import { canAccessBranch } from "@/lib/auth/permissions";
  4. import {
  5. withErrorHandling,
  6. json,
  7. badRequest,
  8. unauthorized,
  9. forbidden,
  10. } from "@/lib/api/errors";
  11. import { mapStorageReadError } from "@/lib/api/storageErrors";
  12. /**
  13. * GET /api/files?branch=&year=&month=&day=
  14. *
  15. * Happy-path response must remain unchanged:
  16. * { "branch":"NL01", "year":"2024", "month":"10", "day":"23", "files":[...] }
  17. */
  18. export const GET = withErrorHandling(
  19. async function GET(request) {
  20. const session = await getSession();
  21. if (!session) {
  22. throw unauthorized("AUTH_UNAUTHENTICATED", "Unauthorized");
  23. }
  24. const { searchParams } = new URL(request.url);
  25. // Query params are required for this endpoint.
  26. const branch = searchParams.get("branch");
  27. const year = searchParams.get("year");
  28. const month = searchParams.get("month");
  29. const day = searchParams.get("day");
  30. const missing = [];
  31. if (!branch) missing.push("branch");
  32. if (!year) missing.push("year");
  33. if (!month) missing.push("month");
  34. if (!day) missing.push("day");
  35. if (missing.length > 0) {
  36. throw badRequest(
  37. "VALIDATION_MISSING_QUERY",
  38. "Missing required query parameter(s)",
  39. { params: missing }
  40. );
  41. }
  42. if (!canAccessBranch(session, branch)) {
  43. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  44. }
  45. try {
  46. const files = await listFiles(branch, year, month, day);
  47. return json({ branch, year, month, day, files }, 200);
  48. } catch (err) {
  49. throw await mapStorageReadError(err, {
  50. details: { branch, year, month, day },
  51. });
  52. }
  53. },
  54. { logPrefix: "[api/files]" }
  55. );