All files / Rindu/utils cookies.ts

47.05% Statements 24/51
38.09% Branches 8/21
40% Functions 4/10
47.91% Lines 23/48

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110  44x                                                   2x 2x 2x 2x     44x                                 53x       58x 58x     58x 57x 57x 57x 12x 12x   11x     46x                     4x                     2x 2x             2x               3x 1x    
import { ServerApiContext } from "types/serverContext";
import { isServer } from "utils";
 
function getArrCookies(cookies: string[]): Record<string, string> {
  const cookiesObject: Record<string, string> = {};
 
  cookies.forEach((cookie) => {
    const [key] = cookie.split(";")[0].split("=");
    cookiesObject[key] = cookie;
  });
  return cookiesObject;
}
 
function getAllServerCookies(context: ServerApiContext) {
  const reqCookies = context.req.cookies;
  const modReqCookies = Object.entries(reqCookies).map(([key, value]) => {
    return `${key}=${value}`;
  });
  const setCookies = context.res.getHeader("Set-Cookie");
  const resCookies =
    setCookies && Array.isArray(setCookies) ? getArrCookies(setCookies) : {};
  const allCookiesObj = Object.assign(modReqCookies, resCookies);
 
  return Object.values(allCookiesObj);
}
 
function getExpires(age?: number) {
  const expireCookieDate = new Date();
  const maxAge = age ?? 60 * 60 * 24 * 30;
  expireCookieDate.setTime(expireCookieDate.getTime() + maxAge * 1000);
  return expireCookieDate.toUTCString();
}
 
const getCookie = (context: ServerApiContext, key: string) => {
  const allCookies = getAllServerCookies(context);
  const cookie = allCookies.find((val) => val.startsWith(`${key}=`));
  Iif (cookie) {
    const cookieParts = cookie.split(";");
    const cookieValue = cookieParts[0].split("=")[1];
    return cookieValue;
  }
  return null;
};
 
/**
 * Get the value of the cookie
 * @param cookieName The name of the cookie to get
 * @param context ServerApiContext
 * @returns value of the cookie string
 */
export function takeCookie(
  cookieName: string | undefined,
  context?: ServerApiContext
): string | null {
  Iif (!cookieName) return null;
  Iif (context && isServer()) {
    const cookie = getCookie(context, cookieName);
    return cookie;
  } else if (global.document) {
    const allCookies = `; ${document.cookie}`;
    const parts = allCookies.split(`; ${cookieName}=`);
    if (parts.length === 2) {
      const cookiesValue = parts.pop()?.split(";").shift();
      if (!cookiesValue) return null;
 
      return cookiesValue;
    }
  }
  return null;
}
 
/**
 * Create a cookie
 * @param {Object} params - The params to create a cookie
 * @param {string} params.name - the name of the cookie to set
 * @param {string} params.value - value
 * @param {number} params.age - the expire time in milliseconds string
 * @param {Object} params.context - ServerApiContext
 */
export function makeCookie({
  name,
  value,
  age,
  context,
}: {
  name: string;
  value: string;
  age?: number;
  context?: ServerApiContext;
}): void {
  const expires = getExpires(age);
  Iif (context) {
    const setCookies = context.res.getHeader("Set-Cookie");
    const cookies =
      setCookies && Array.isArray(setCookies) ? getArrCookies(setCookies) : {};
    const val = `${name}=${value}; Path=/; expires=${expires}; SameSite=Lax; Secure;`;
    context.res.setHeader("Set-Cookie", [...Object.values(cookies), val]);
  } else {
    document.cookie = `${name}=${value}; Expires=${expires}; Path=/; SameSite=lax; Secure;`;
  }
}
 
/**
 * Remove a cookie
 * @param cookieName the name of the cookie to remove
 */
export function eatCookie(cookieName: string): void {
  document.cookie = `${cookieName}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Lax;`;
}