github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/src/util/query.ts (about)

     1  // Copyright 2019 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  import { Location } from "history";
    12  import { match as Match } from "react-router-dom";
    13  
    14  interface ParamsObj {
    15    [key: string]: string;
    16  }
    17  
    18  interface URLSearchParamsWithKeys extends URLSearchParams {
    19    keys: () => string;
    20  }
    21  
    22  /* eslint-disable no-prototype-builtins,no-restricted-syntax */
    23  export function queryToString(obj: any) {
    24    const str = [];
    25    for (const p in obj) {
    26      if (obj.hasOwnProperty(p)) {
    27        str.push(`${encodeURIComponent(p)}=${encodeURIComponent(obj[p])}`);
    28      }
    29    }
    30    return str.join("&");
    31  }
    32  
    33  export function queryToObj(location: Location, key: string, value: string) {
    34    const params = new URLSearchParams(location.search) as URLSearchParamsWithKeys;
    35    const paramObj: ParamsObj = {};
    36    for (const data of params.keys()) {
    37      paramObj[data] = params.get(data);
    38    }
    39    if (key && value) {
    40      if (value.length > 0 || (typeof value === "number")) {
    41        paramObj[key] = value;
    42      } else {
    43        delete paramObj[key];
    44      }
    45    }
    46    return paramObj;
    47  }
    48  
    49  export function queryByName(location: Location, key: string) {
    50    const urlParams = new URLSearchParams(location.search);
    51    return urlParams.get(key);
    52  }
    53  
    54  export function getMatchParamByName(match: Match<any>, key: string ) {
    55    const param = match.params[key];
    56    if (param) {
    57      return decodeURIComponent(param);
    58    }
    59    return null;
    60  }