This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
QueryBuilder.ts
111 lines (95 loc) · 2.42 KB
/
QueryBuilder.ts
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
*/
import {Type} from "../Types";
import {OrderedStringKeyDictionary} from "../Collections/Dictionaries/OrderedStringKeyDictionary";
import {isEnumerableOrArrayLike} from "../Collections/Enumeration/Enumerator";
import {UriComponent} from "./UriComponent";
import {QueryParam} from "./QueryParam";
import {encode, parse} from "./QueryParams";
import __extendsImport from "../../extends";
// noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
/**
* Provides a means for parsing and building a set of parameters.
*
* In other languages, dictionaries are not reliable for retaining the order of stored values. So for certainty and flexibility we use an ordered dictionary as a base class.
*/
export class QueryBuilder extends OrderedStringKeyDictionary<UriComponent.Value|UriComponent.Value[]>
{
constructor(
query:QueryParam.Convertible,
decodeValues:boolean = true)
{
super();
this.importQuery(query, decodeValues);
}
static init(
query:QueryParam.Convertible,
decodeValues:boolean = true):QueryBuilder
{
return new QueryBuilder(query, decodeValues);
}
importQuery(
query:QueryParam.Convertible,
decodeValues:boolean = true):QueryBuilder
{
if(Type.isString(query))
{
this.importFromString(<string>query, decodeValues);
}
else if(isEnumerableOrArrayLike(query))
{
this.importEntries(query);
}
else
{
this.importMap(<UriComponent.Map>query);
}
return this;
}
/**
* Property parses the components of an URI into their values or array of values.
* @param values
* @param deserialize
* @param decodeValues
* @returns {QueryBuilder}
*/
importFromString(
values:string,
deserialize:boolean = true,
decodeValues:boolean = true):QueryBuilder
{
const _ = this;
parse(values,
(key, value)=>
{
if(_.containsKey(key))
{
const prev = _.getValue(key);
if((prev)instanceof(Array))
prev.push(value);
else
_.setValue(key, [<UriComponent.Value>prev, value]);
}
else
_.setValue(key, value);
},
deserialize,
decodeValues);
return this;
}
/**
* Returns the encoded URI string
*/
encode(prefixIfNotEmpty?:boolean):string
{
return encode(this, prefixIfNotEmpty);
}
toString():string
{
return this.encode();
}
}
export default QueryBuilder;