import cookies from "cookies-js";

export default {
  get(key) {
    let result = window.localStorage.getItem(key);
    // 如果本地存储拿不到tokenn，那就去cookies拿
    if (!result && key === "mongoToken") {
      return cookies.get(key) || "";
    }
    try {
      return JSON.parse(result);
    } catch (e) {
      return result;
    }
  },
  set(key, value) {
    if (value === undefined) return;
    let toString = Object.prototype.toString;
    if (toString.call(value) === "[object Array]" || toString.call(value) === "[object Object]") {
      value = JSON.stringify(value);
    }
    // token存cookies一份，做备份
    if (key === "mongoToken") {
      cookies.set(key, value, { expires: "01/01/2030" });
    }
    return window.localStorage.setItem(key, value);
  },
  remove(key) {
    return window.localStorage.removeItem(key);
  },
  clear() {
    return window.localStorage.clear();
  }
};
