All files / src/services/api/routers UserRouter.tsx

72.72% Statements 16/22
71.42% Branches 10/14
80% Functions 4/5
77.77% Lines 14/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 51 52 53 54 55 56 57 58 59 60 61 62 63                          2209x               2209x 3x 3x 3x 3x                     2209x 3x 3x             2209x     3x           3x 3x       3x      
import { APIRouter } from "../ApiRouter";
import { Dictionary } from "@/types/ext";
import { AxiosRequestConfig } from "axios";
import { CoreUser } from "@/objects/CoreUser";
import { dispositionFilename, saveBlob } from "@/util/download";
 
export class UserRouter extends APIRouter {
  constructor(
    host: string,
    token: string | null = null,
    default_config: AxiosRequestConfig | null = null,
    headers: Dictionary<string> = {},
  ) {
    super("users", host, token, default_config, headers);
  }
 
  /**
   * Check whether the authenticated session is provisioned in svc-core.
   * Returns the CoreUser on success, null if not yet provisioned (404),
   * or throws for other errors.
   */
  me = async (): Promise<CoreUser | null> => {
    try {
      const res = await this.api.get(this.endpoint("me"));
      Iif (res.status === 404) return null;
      Eif (super.validRes(res)) return res.data as CoreUser;
      return null;
    } catch {
      return null;
    }
  };
 
  /**
   * Provision the current session as a svc-core user.
   * Called once during onboarding.
   */
  provision = async (name: string): Promise<CoreUser | null> => {
    const res = await this.api.post(this.endpoint("me"), { name });
    Eif (super.validRes(res)) return res.data as CoreUser;
    return null;
  };
 
  /** Download a zip of everything the caller owns. svc-core builds it in
   *  full before answering, so this can take a while for a large account.
   *  Resolves false when the download failed. */
  downloadExport = async (
    fallbackName = "chainr-export.zip",
  ): Promise<boolean> => {
    const res = await this.api
      .get(this.endpoint("me/export"), {
        responseType: "blob",
        withCredentials: true,
      })
      .catch(() => null);
    Iif (res?.status !== 200) return false;
    saveBlob(
      res.data as Blob,
      dispositionFilename(res.headers?.["content-disposition"]) ?? fallbackName,
    );
    return true;
  };
}