/
angularODataUtils.ts
55 lines (46 loc) · 1.68 KB
/
angularODataUtils.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
export class ODataUtils {
public static convertObjectToString(obj: any): string {
const properties: string[] = [];
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && obj[prop] !== undefined) {
const value: any = ODataUtils.quoteValue(obj[prop]);
properties.push(`${prop}=${value}`);
}
}
return properties.join(', ');
}
public static quoteValue(value: number | string | boolean | any): string {
// check if GUID (UUID) type
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
return value;
}
// check if string
if (typeof value === 'string') {
const escaped = value.replace(/'/g, '\'\'');
return `'${escaped}'`;
}
// check if boolean or number
if (typeof value === 'boolean' || typeof value === 'number') {
return `${value}`;
}
const parts: string[] = [];
Object.getOwnPropertyNames(value).forEach((propertyName: string) => {
const propertyValue: any = value[propertyName];
parts.push(`${propertyName}=${ODataUtils.quoteValue(propertyValue)}`);
});
return parts.length > 0 ? parts.join(', ') : `${value}`;
}
public static tryParseInt(input?: any): { valid: boolean, value: number } {
if (input !== null && !isNaN(input)) {
const parsed: number = parseInt(input, 10);
return {
valid: !isNaN(parsed),
value: parsed
};
}
return {
valid: false,
value: NaN
};
}
}