route.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { IS_PLATFORM } from 'common'
  2. import { NextResponse } from 'next/server'
  3. import { InternalServerError } from '@/lib/api/apiHelpers'
  4. import { getBannerIncidents } from '@/lib/api/incident-banner'
  5. /**
  6. * Cache on CDN for 5 minutes
  7. * Allow serving stale content for 1 minute while revalidating
  8. */
  9. const CACHE_CONTROL_SETTINGS = 'public, s-maxage=300, stale-while-revalidate=60'
  10. export async function OPTIONS() {
  11. if (!IS_PLATFORM) return new Response(null, { status: 404 })
  12. return new Response(null, {
  13. status: 204,
  14. headers: {
  15. Allow: 'GET, HEAD, OPTIONS',
  16. },
  17. })
  18. }
  19. export async function HEAD() {
  20. if (!IS_PLATFORM) return new Response(null, { status: 404 })
  21. return new Response(null, {
  22. status: 200,
  23. headers: { 'Cache-Control': CACHE_CONTROL_SETTINGS },
  24. })
  25. }
  26. export async function GET() {
  27. if (!IS_PLATFORM) return new Response(null, { status: 404 })
  28. try {
  29. const incidents = await getBannerIncidents()
  30. return NextResponse.json(
  31. { incidents },
  32. { headers: { 'Cache-Control': CACHE_CONTROL_SETTINGS } }
  33. )
  34. } catch (error) {
  35. let errorCode = 500
  36. const headers = new Headers()
  37. if (error instanceof InternalServerError) {
  38. if (typeof error.details?.status === 'number') errorCode = error.details.status
  39. if (errorCode === 420) errorCode = 429
  40. if (errorCode === 429 && typeof error.details?.retryAfter === 'string') {
  41. headers.set('Retry-After', error.details.retryAfter)
  42. }
  43. console.error('Failed to fetch incident.io incidents: %O', {
  44. message: error.message,
  45. details: error.details,
  46. })
  47. } else {
  48. console.error('Unexpected error fetching incident.io incidents: %O', error)
  49. }
  50. return NextResponse.json(
  51. { error: { message: 'Internal server error' } },
  52. { status: errorCode, headers }
  53. )
  54. }
  55. }