forked from openid/AppAuth-JS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_string_utils.ts
More file actions
64 lines (58 loc) · 1.97 KB
/
Copy pathquery_string_utils.ts
File metadata and controls
64 lines (58 loc) · 1.97 KB
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
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
import {LocationLike, StringMap} from './types';
/**
* Query String Utilities.
*/
export interface QueryStringUtils {
stringify(input: StringMap): string;
parse(query: LocationLike, useHash?: boolean): StringMap;
parseQueryString(query: string): StringMap;
}
export class BasicQueryStringUtils implements QueryStringUtils {
parse(input: LocationLike, useHash?: boolean) {
if (useHash) {
return this.parseQueryString(input.hash);
} else {
return this.parseQueryString(input.search);
}
}
parseQueryString(query: string): StringMap {
let result: StringMap = {};
// if anything starts with ?, # or & remove it
query = query.trim().replace(/^(\?|#|&)/, '');
let params = query.split('&');
for (let i = 0; i < params.length; i += 1) {
let param = params[i]; // looks something like a=b
let parts = param.split('=');
if (parts.length >= 2) {
let key = decodeURIComponent(parts.shift()!);
let value = parts.length > 0 ? parts.join('=') : null;
if (value) {
result[key] = decodeURIComponent(value);
}
}
}
return result;
}
stringify(input: StringMap) {
let encoded: string[] = [];
for (let key in input) {
if (input.hasOwnProperty(key) && input[key]) {
encoded.push(`${encodeURIComponent(key)}=${encodeURIComponent(input[key])}`)
}
}
return encoded.join('&');
}
}