All files index.js

95.24% Statements 20/21
81.82% Branches 9/11
100% Functions 10/10
95.24% Lines 20/21

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                                                    13x 13x       1x 1x 1x       2x 2x 2x       2x       2x       2x       2x       2x 2x             2x         3x 3x           8x 8x 8x    
// @flow
 
import queryString from 'query-string';
 
type HistoryType = {
  location: {
    pathname: string,
    search: string
  },
  push: string => void
};
 
type GoToParamsType = {
  pathname: string,
  operator?: 'create' | 'update',
  payload?: Object,
  where?: Object,
  sort?: Object,
  pagination?: Object
};
 
export default class HistoryRouter {
  baseUrl: string;
  history: HistoryType;
 
  constructor({baseUrl = '/', history}: {baseUrl: string, history: HistoryType}) {
    this.baseUrl = baseUrl;
    this.history = history;
  }
 
  getRoutes = () => {
    const {location: {pathname}} = this.history;
    const pathnameWithoutBaseUrl = pathname.substring(this.baseUrl.length);
    return deleteFirstSlash(pathnameWithoutBaseUrl).split('/');
  }
 
  getOperator = () => {
    const {location: {search}} = this.history;
    const qs = queryString.parse(search);
    return qs.operator || 'update';
  }
 
  getPayload = () => {
    return getUrlObjectParams(this.history, 'payload');
  }
 
  getWhere = () => {
    return getUrlObjectParams(this.history, 'where');
  }
 
  getSort = () => {
    return getUrlObjectParams(this.history, 'sort');
  }
 
  getPagination = () => {
    return getUrlObjectParams(this.history, 'pagination');
  }
 
  goTo = ({pathname, operator, payload, where, sort, pagination}: GoToParamsType) => {
    const pathnameWithoutFirstSlash = deleteFirstSlash(pathname);
    const qs = queryString.stringify({
      operator,
      payload: JSON.stringify(payload),
      where: JSON.stringify(where),
      sort: JSON.stringify(sort),
      pagination: JSON.stringify(pagination),
    });
    this.history.push(`${this.baseUrl}/${pathnameWithoutFirstSlash}${qs ? `?${qs}` : ''}`);
  }
}
 
function deleteFirstSlash(path) {
  Eif (path && path[0] === '/') {
    return path.substring(1);
  }
  return path;
}
 
function getUrlObjectParams(history, key) {
  const {location: {search}} = history;
  const qs = queryString.parse(search);
  return qs[key] ? JSON.parse(qs[key]) : {};
}