Skip to content

Commit

Permalink
refactor(ping): make the code more manageable
Browse files Browse the repository at this point in the history
  • Loading branch information
Veirt committed Jun 11, 2024
1 parent f7287d8 commit 0261216
Showing 1 changed file with 15 additions and 28 deletions.
43 changes: 15 additions & 28 deletions src/routes/api/ping/+server.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,34 @@
import { getWidgetInfo } from "$lib/utils/widget";
import { json, type RequestHandler } from "@sveltejs/kit";
import axios, { isAxiosError } from "axios";
import axios from "axios";
import https from "https";

const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
const instance = axios.create({
httpsAgent,
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
validateStatus() {
return true;
},
});

async function checkWebsiteStatus(pingUrl: string) {
let response = await instance.head(pingUrl);
if (response.status === 501) {
// Use GET if HEAD is not implemented
response = await instance.get(pingUrl);
}

return response.status;
}

export const GET = (async ({ url }) => {
const group = url.searchParams.get("group")!;
const title = url.searchParams.get("title")!;

const { url: pingUrl } = getWidgetInfo(group, title).ping!;

if (!pingUrl) {
return json({
error: "ping.url is undefined",
});
}

let statusCode;
try {
let res;
res = await instance.head(pingUrl);

// use GET instead of HEAD when HEAD is not implemented
if (res.status === 501) {
res = await instance.get(pingUrl);
}
statusCode = res.status;
const statusCode = await checkWebsiteStatus(pingUrl);
return json({ statusCode });
} catch (error) {
if (isAxiosError(error)) {
return json({ error: error.message });
} else {
return json({ error });
}
return json({ error });
}

return json({ statusCode });
}) satisfies RequestHandler;

0 comments on commit 0261216

Please sign in to comment.