helper.js 5.8 KB
/* eslint-disable no-param-reassign */
import moment from 'moment';
import pickBy from 'lodash/pickBy';
import negate from 'lodash/negate';
import isUndefined from 'lodash/isUndefined';
import resolvePathname from 'resolve-pathname';
import { createJSEncrypt } from './jsencrypt';
import config from './config';

const { contextPath, pubKey } = config;

const toKey = (key) => {
  let ret = key.replace(/(_{2,})/g, '$1_');
  ret = ret.replace(/-/g, '__');
  if (!/^\w+$/.test(ret)) {
    throw new Error(`Invalid cookie key: ${key}.`);
  }
  return ret;
};

export function setCookie(name, value, options = {}) {
  const { path, domain, expires } = options;
  name = toKey(name);
  if (name) {
    const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : '';
    const domainSet = domain ? ` domain=${domain};` : '';
    const pathSet = path ? ` path=${path};` : ' path=/;';
    const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
    document.cookie = `${valueSet}${expireSet}${domainSet}${pathSet}`; // eslint-disable-line
  }
}

export function getCookie(name) {
  name = toKey(name);
  const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`, 'g');
  const arr = document.cookie.match(reg); // eslint-disable-line
  if (arr) {
    let value = arr.map(v => v.substring(`${name}=`.length).trim()).filter(v => !!v).pop();
    if (value.endsWith(';')) {
      value = value.substring(0, value.length - 1);
    }
    return decodeURIComponent(value);
  } else {
    return null;
  }
}

export function delCookie(name, { domain, path } = {}) {
  if (getCookie(name)) {
    name = toKey(name);
    const domainSet = domain ? ` domain=${domain};` : '';
    const pathSet = path ? ` path=${path};` : ' path=/';
    document.cookie = `${name}=; expires=Thu, 01-Jan-70 00:00:01 GMT;${pathSet}${domainSet}`; // eslint-disable-line
  }
}

export function setLocalStorge(key, value) {
  return localStorage.setItem(key, JSON.stringify(value)); // eslint-disable-line
}

export function getLocalStorge(key) {
  return JSON.parse(localStorage.getItem(key)); // eslint-disable-line
}

export function delLocalStorge(key) {
  return localStorage.removeItem(key); // eslint-disable-line
}

export function locationOrigin(withContext = true) {
  return `${location.protocol}//${location.hostname}${location.port ? ':' + location.port : ''}${withContext ? contextPath : ''}`; // eslint-disable-line
}

export const makeSureEndsWithSlash = (path) => {
  if (!path || !path.endsWith('/')) {
    return `${path || ''}/`;
  } else {
    return path;
  }
};

const makeSureStartsWithSlash = (path) => {
  if (!path || !path.startsWith('/')) {
    return `/${path || ''}`;
  } else {
    return path;
  }
};

export const makePath = (base, path, withContext = false) => {
  if (path.startsWith('/')) {
    return withContext ? `${contextPath}${path}` : path;
  }
  const basePath = makeSureEndsWithSlash(base);
  return resolvePathname(path, basePath);
};

export function currentPath() {
  let path = location.pathname; // eslint-disable-line
  path = makeSureStartsWithSlash(path);
  if (path.slice(0, contextPath.length) === contextPath) {
    return makeSureStartsWithSlash(path.slice(contextPath.length));
  } else {
    return path;
  }
}

export function encrypt(text) {
  const jsEncrypt = createJSEncrypt();
  jsEncrypt.setPublicKey(pubKey);
  let out = jsEncrypt.encryptLong(text);
  out = out.split('=')[0];
  out = out.replace(/\+/g, '-');
  return out.replace(/\//g, '_');
}

/**
 * @param name {String}
 * @return  {String}
 */
export function queryURL(name) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  // eslint-disable-next-line no-undef
  const r = window ? window.location.search.substr(1).match(reg) : null;
  if (r !== null) return decodeURI(r[2]);
  return null;
}

export function padDigits(number, digits) {
  return new Array(Math.max(digits - String(number).length + 1, 0)).join('0') + number;
}

export function is(obj, type) {
  return (type === 'Null' && obj === null)
    || (type === 'Undefined' && obj === void 0) // eslint-disable-line no-void
    || (type === 'Number' && Number.isFinite(obj))
    || Object.prototype.toString.call(obj).slice(8, -1) === type;
}

export function makePromise0(thunk) {
  return new Promise((resolve) => {
    thunk(data => resolve(data));
  });
}

export function makePromise1(thunk) {
  return new Promise((resolve, reject) => {
    thunk(err => reject(err), data => resolve(data));
  });
}

export function filterValidParams(params) {
  return pickBy(params, negate(isUndefined));
}

export function isPromise(obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}

export function shallowEqual(o1, o2, excludes = []) {
  if (o1 === o2) {
    return true;
  }
  if (typeof o1 !== 'object' || typeof o2 !== 'object' || o1 === null || o2 === null) {
    return false;
  }
  if (Array.isArray(o1) && Array.isArray(o2)) {
    const len = o1.length;
    if (len !== o2.length) {
      return false;
    }
    for (let i = 0; i < len; ++i) {
      if (o1[i] !== o2[i]) {
        return false;
      }
    }
    return true;
  }
  const keys1 = Object.keys(o1);
  const keys2 = Object.keys(o2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  for (let i = 0; i < keys1.length; ++i) {
    const key = keys1[i];
    if (!excludes.includes(key) && (!keys2.includes(key) || o1[key] !== o2[key])) {
      return false;
    }
  }
  return true;
}

export const mapObject = (obj, mapper) => {
  const newObj = {};
  for (const key of Object.keys(obj)) {
    newObj[key] = mapper(obj[key], key);
  }
  return newObj;
};

export const arrayJoin = (arr, joined) => {
  const newArr = [];
  for (let i = 0; i < arr.length; ++i) {
    newArr.push(arr[i]);
    newArr.push(joined);
  }
  if (newArr.length > 0) {
    newArr.pop();
  }
  return newArr;
};