All files / react/session refresh.js

5.55% Statements 1/18
0% Branches 0/7
0% Functions 0/3
5.55% Lines 1/18

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                    3x                                                                              
import { parse } from "cookie";
import logoutSession from "./logout.js";
 
/**
 * Makes an API request to refresh the session token cookie, if it exists.
 * @param {Object}   [options] - Optional configuration parameters.
 * @param {function} [options.onSuccess] - An optional success callback.
 * @param {function} [options.onError] - An optional error callback.
 * @return {Function} Returns a promise
 */
const refreshSession = async (options = {}) => {
  const url = "/api/auth/sessions/refresh";
  let cookies = parse(window.document.cookie);
  const headers = new Headers({
    Accept: `application/vnd.qpp.cms.gov.v2+json`,
    "Content-Type": "application/json",
    Authorization: `Bearer ${cookies.qpp_auth_token}`,
  });
  const fetchOptions = {
    method: "POST",
    headers,
  };
 
  const onSuccess = () => {
    if (typeof options.onSuccess === "function") {
      options.onSuccess();
    }
  };
 
  const onError = () => {
    if (typeof options.onError === "function") {
      options.onError();
    }
 
    return logoutSession(window);  
  };
 
  try {
    const response = await fetch(url, fetchOptions);
    if (response.ok) {
      return onSuccess();
    }
    throw new Error("Unable to refresh session");
  } catch {
    onError();
  }
};
 
export default refreshSession;