-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(ping): make the code more manageable
- Loading branch information
Showing
1 changed file
with
15 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |