Skip to content

Instantly share code, notes, and snippets.

@navin-moorthy
Last active August 11, 2023 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navin-moorthy/78e36a7f20fd1259303b20b1b3543779 to your computer and use it in GitHub Desktop.
Save navin-moorthy/78e36a7f20fd1259303b20b1b3543779 to your computer and use it in GitHub Desktop.
Browser Utils
import { isNonNullable } from "isNonNullable";
export type GetFinalLogoSizeProps = { width: number; height: number; maxHeight: number; maxWidth: number };
export const getFinalLogoSize = ({ width, height, maxHeight, maxWidth }: GetFinalLogoSizeProps) => {
if (isNonNullable(maxHeight) && !isNonNullable(maxWidth)) {
return {
width: Math.floor(width * (maxHeight / height)),
height: maxHeight,
};
}
if (isNonNullable(maxWidth) && !isNonNullable(maxHeight)) {
return { width: maxWidth, height: Math.floor(height * (maxWidth / width)) };
}
if (!isNonNullable(maxHeight)) {
return { width, height };
}
if (!isNonNullable(maxWidth)) {
return { width, height };
}
const maxHeightWidth = Math.floor(height * (maxWidth / width));
const maxWidthHeight = Math.floor(width * (maxHeight / height));
if (maxHeightWidth <= maxHeight) {
return { width: maxWidth, height: maxHeightWidth };
}
return { width: maxWidthHeight, height: maxHeight };
};
/**
* Check if we're on the server or client side
*/
export const isBrowser =
typeof window !== "undefined" &&
typeof navigator !== "undefined" &&
typeof document !== "undefined" &&
window.document !== undefined &&
window.document.createElement !== undefined;
import kyDefault from "ky-universal";
class HTTPError extends Error {}
export const ky = kyDefault.extend({
timeout: 5000,
retry: 3,
hooks: {
// https://twitter.com/oscarbastos_web/status/1689705853249605634/photo/1
beforeRetry: [
(_, _1, _2, retryCount) => {
if (process.env.NODE_ENV === "development") {
console.log(`Retrying request attempt ${retryCount + 1} times...`);
}
},
],
afterResponse: [
async (_, _1, response) => {
if (!response.ok) {
if (
response.headers.get("content-type")?.includes("application/json")
) {
const errorResponseJson = await response.json();
if (process.env.NODE_ENV === "development") {
console.error(errorResponseJson.message);
return;
} else {
throw new HTTPError(
`Fetch error ${response.status}: ${response.statusText} in ${response.url} failed}`
);
}
}
const errorResponseText = await response.text();
if (process.env.NODE_ENV === "development") {
console.error(errorResponseText);
} else {
throw new HTTPError(
`Fetch error ${response.status}: ${response.statusText} in ${response.url} failed}`
);
}
}
},
],
},
});
import { addAdditionalErrorMessage } from "./addAdditionalErrorMessage";
import { ky } from "./ky";
export const kyGetFetcher = async <T>(url: string) => {
try {
return await ky.get(url).json<T>();
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error(
addAdditionalErrorMessage(
error,
`Fetching ${url} using kyGetFetcher failed`,
),
);
} else {
console.error(error);
}
throw new Error(`Failed to fetch ${url}`);
}
};
import { type Options } from "ky";
import { addAdditionalErrorMessage } from "./addAdditionalErrorMessage";
import { ky } from "./ky";
export const kyPostFetcher = async <T>(url: string, options: Options) => {
try {
return await ky.post(url, options).json<T>();
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error(
addAdditionalErrorMessage(
error,
`Fetching ${url} using kyPostFetcher failed`,
),
);
} else {
console.error(error);
}
throw new Error(`Failed to fetch ${url}`);
}
};
export function useGistFetch(gistId?: string): string | null {
const [data, setData] = useState<string | null>(null);
// Fetch the data here
useEffect(() => {
if (!gistId) return;
const fetchData = async (): Promise<void> => {
try {
const res = await fetch(`https://api.github.com/gists/${gistId}`, {
headers: {
Accept: "application/vnd.github.v3+json",
// @ts-ignore
Authorization: `token ${import.meta.env.VITE_GITHUB_CREATE_GIST}`,
},
});
const resJson = (await res.json()) as GistResponse;
const themeJson = resJson.files["theme.json"].content;
setData(themeJson);
} catch (error) {
console.log(error);
}
};
fetchData()
.then(() => console.log("Fetch Successfull"))
.catch((error) => console.log("Error Fetching", error));
}, [gistId]);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment