Skip to content

Commit

Permalink
✨ Add timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed May 14, 2020
1 parent 03da2fd commit 67f98ed
Showing 1 changed file with 46 additions and 4 deletions.
50 changes: 46 additions & 4 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,51 @@
/** Check if you are online and connected to the internet */
export async function isOnline(
{ timeout, family }: { timeout?: number; family?: number },
export interface OnlineParams {
timeout?: number;
}

/**
* Timeout a Promise after a duration
* @param ms - Number of miliseconds
* @param promise - Promise to return
* @source https://github.com/github/fetch/issues/175#issuecomment-216791333
*/
function timeoutPromise(
ms: number,
promise: Promise<boolean>,
): Promise<boolean> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
resolve(false);
}, ms);
promise.then(
(res) => {
clearTimeout(timeoutId);
resolve(res);
},
(err) => {
clearTimeout(timeoutId);
resolve(false);
},
);
});
}

async function checkOnline(
params?: OnlineParams,
): Promise<boolean> {
const text =
await (await (await fetch("http://captive.apple.com/hotspot-detect.html"))
await (await (await fetch("http://captive.apple.com/hotspot-detect.html", {
headers: {
"User-Agent": "CaptiveNetworkSupport/1.0 wispr",
},
}))
.blob()).text();
return (text ?? "").toLowerCase().includes("success");
}

/** Check if you are online and connected to the internet */
export function isOnline(params?: OnlineParams) {
if (params?.timeout) {
return timeoutPromise(params.timeout, checkOnline(params));
}
return checkOnline(params);
}

0 comments on commit 67f98ed

Please sign in to comment.