1import invariant from 'invariant';
2import qs from 'qs';
3
4export function buildQueryString(input: Record<string, string>): string {
5  return qs.stringify(input);
6}
7
8export function getQueryParams(url: string): {
9  errorCode: string | null;
10  params: { [key: string]: string };
11} {
12  const parts = url.split('#');
13  const hash = parts[1];
14  const partsWithoutHash = parts[0].split('?');
15  const queryString = partsWithoutHash[partsWithoutHash.length - 1];
16
17  // Get query string (?hello=world)
18  const parsedSearch = qs.parse(queryString, { parseArrays: false });
19
20  // Pull errorCode off of params
21  const errorCode = (parsedSearch.errorCode ?? null) as string | null;
22  invariant(
23    typeof errorCode === 'string' || errorCode === null,
24    `The "errorCode" parameter must be a string if specified`
25  );
26  delete parsedSearch.errorCode;
27
28  // Get hash (#abc=example)
29  let parsedHash = {};
30  if (parts[1]) {
31    parsedHash = qs.parse(hash);
32  }
33
34  // Merge search and hash
35  const params = {
36    ...parsedSearch,
37    ...parsedHash,
38  };
39
40  return {
41    errorCode,
42    params,
43  };
44}
45