-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a16682e
commit 8cc78a5
Showing
4 changed files
with
48 additions
and
56 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
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 |
---|---|---|
@@ -0,0 +1,45 @@ | ||
export interface Resp { | ||
status: number | undefined; | ||
data: any; | ||
} | ||
|
||
const inBrowser = | ||
typeof window !== "undefined" && typeof window.fetch !== "undefined"; | ||
const inNode = | ||
typeof process !== "undefined" && | ||
process.versions != null && | ||
process.versions.node != null; | ||
|
||
export async function get(url: string): Promise<Resp> { | ||
if (inBrowser) { | ||
const response = await window.fetch(url); | ||
|
||
return { | ||
status: response.status, | ||
data: await response.json(), | ||
}; | ||
} else if (inNode) { | ||
const getter = url.startsWith("https") | ||
? await import("https") | ||
: await import("http"); | ||
|
||
return await new Promise((res, rej) => { | ||
const request = getter.get(url, (response) => { | ||
let data = ""; | ||
response.on("error", rej); | ||
response.on("data", (chunk) => (data += chunk.toString())); | ||
response.on("end", () => | ||
res({ | ||
status: response.statusCode, | ||
data: JSON.parse(data), | ||
}) | ||
); | ||
}); | ||
|
||
request.on("error", rej); | ||
request.end(); | ||
}); | ||
} else { | ||
throw new Error("Unknown environment"); | ||
} | ||
} |