-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
odata.ts
51 lines (45 loc) · 1.5 KB
/
odata.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
function formatNullAndUndefined(input: unknown): string | unknown {
if (input === null || input === undefined) {
return "null";
}
return input;
}
function escapeQuotesIfString(input: unknown, previous: string): string | unknown {
let result = input;
if (typeof input === "string") {
result = input.replace(/'/g, "''");
// check if we need to escape this literal
if (!previous.trim().endsWith("'")) {
result = `'${result}'`;
}
}
return result;
}
/**
* Escapes an odata filter expression to avoid errors with quoting string literals.
* Example usage:
* ```ts
* const baseRateMax = 200;
* const ratingMin = 4;
* const filter = odata`Rooms/any(room: room/BaseRate lt ${baseRateMax}) and Rating ge ${ratingMin}`;
* ```
* For more information on supported syntax see: https://docs.microsoft.com/en-us/azure/search/search-query-odata-filter
* @param strings - Array of strings for the expression
* @param values - Array of values for the expression
*/
export function odata(strings: TemplateStringsArray, ...values: unknown[]): string {
const results = [];
for (let i = 0; i < strings.length; i++) {
results.push(strings[i]);
if (i < values.length) {
if (values[i] === null || values[i] === undefined) {
results.push(formatNullAndUndefined(values[i]));
} else {
results.push(escapeQuotesIfString(values[i], strings[i]));
}
}
}
return results.join("");
}