All files / src/utils assets.ts

32.43% Statements 12/37
0% Branches 0/20
20% Functions 2/10
35.48% Lines 11/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73      52x                           52x       52x       6x 6x 78x 6x 6x     52x               52x                               52x                                
import { VIDEO_BASE_URL } from "@constants/constants";
import { isMobile } from ".";
 
export const buildAssetsUrl = (
  domain: string,
  path: string,
  fileType: string,
  shoudlRenderMobile: boolean,
  mobilePattern: string,
) => {
  const extension =
    shoudlRenderMobile && isMobile
      ? `${mobilePattern}.${fileType}`
      : `.${fileType}`;
  return `${domain}/${path}${extension}`;
};
 
export const buildCompaignAndBannerVideo = (path: string) => {
  return buildAssetsUrl(VIDEO_BASE_URL, path, "mp4", true, "-mobile");
};
 
export const dataURLtoFile = async (
  base64String: string,
  fileName: string,
): Promise<File> => {
  const pureBase64String = base64String.split(",")[1];
  const binaryString = atob(pureBase64String);
  const arr = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
  const blob = new Blob([arr], { type: "image/png" });
  return new File([blob], fileName, { type: "image/png" });
};
 
export const fileToBase64 = (file: File) =>
  new Promise(function (resolve, reject) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
 
export const urlToBase64 = async (
  url?: string,
  name?: string,
  fileType?: string,
) => {
  if (!url) return undefined;
  const response = await fetch(url);
  if (!response.ok) return undefined;
  const data = await response.blob();
  const file = new File([data], name || "image", {
    type: fileType || data?.type,
  });
  const base64 = await fileToBase64(file);
  return base64;
};
 
export const createFileFromURL = async (
  url: string,
  fileName = "image",
  type?: any,
  withCredentials = true,
) => {
  const response = await fetch(
    url,
    withCredentials ? { credentials: "include" } : undefined,
  );
  if (!response.ok) return undefined;
  const blob = await response.blob();
 
  const file = new File([blob], fileName, { type: type || blob.type });
  return file;
};