Openstatus www.openstatus.dev
at main 71 lines 1.8 kB view raw
1import { NextResponse } from "next/server"; 2import { z } from "zod"; 3 4import { 5 type Region, 6 monitorRegionSchema, 7} from "@openstatus/db/src/schema/constants"; 8 9import { TCPResponse, tcpPayload } from "./schema"; 10 11export const runtime = "edge"; 12export const preferredRegion = "auto"; 13export const dynamic = "force-dynamic"; 14export const revalidate = 0; 15 16export function GET() { 17 return NextResponse.json({ success: true }); 18} 19 20export async function POST(request: Request) { 21 try { 22 const json = await request.json(); 23 const _valid = tcpPayload 24 .pick({ url: true }) 25 .extend(z.object({ region: monitorRegionSchema.prefault("ams") }).shape) 26 .safeParse(json); 27 28 if (!_valid.success) { 29 return NextResponse.json({ success: false }, { status: 400 }); 30 } 31 32 const { url, region } = _valid.data; 33 34 const res = await checkTCP(url, region); 35 36 return NextResponse.json(res); 37 } catch (e) { 38 console.error(e); 39 return NextResponse.json({ success: false }, { status: 400 }); 40 } 41} 42async function checkTCP(url: string, region: Region) { 43 // 44 const res = await fetch(`https://checker.openstatus.dev/tcp/${region}`, { 45 headers: { 46 Authorization: `Basic ${process.env.CRON_SECRET}`, 47 "Content-Type": "application/json", 48 "fly-prefer-region": region, 49 }, 50 method: "POST", 51 body: JSON.stringify({ 52 uri: url, 53 }), 54 next: { revalidate: 0 }, 55 }); 56 57 const json = await res.json(); 58 59 const data = TCPResponse.safeParse(json); 60 61 if (!data.success) { 62 console.error(res); 63 console.error(JSON.stringify(json)); 64 console.error( 65 `something went wrong with request to ${url} error ${data.error.message}`, 66 ); 67 throw new Error(data.error.message); 68 } 69 70 return data.data; 71}