refs #14007 Merge branch 'origin/14007-ts-paths'
[arvados.git] / src / common / api / filter-builder.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as _ from "lodash";
6
7 export class FilterBuilder {
8     static create(resourcePrefix = "") {
9         return new FilterBuilder(resourcePrefix);
10     }
11
12     constructor(
13         private resourcePrefix = "",
14         private filters = "") { }
15
16     public addEqual(field: string, value?: string) {
17         return this.addCondition(field, "=", value);
18     }
19
20     public addLike(field: string, value?: string) {
21         return this.addCondition(field, "like", value, "%", "%");
22     }
23
24     public addILike(field: string, value?: string) {
25         return this.addCondition(field, "ilike", value, "%", "%");
26     }
27
28     public addIsA(field: string, value?: string | string[]) {
29         return this.addCondition(field, "is_a", value);
30     }
31
32     public addIn(field: string, value?: string | string[]) {
33         return this.addCondition(field, "in", value);
34     }
35
36     public concat(filterBuilder: FilterBuilder) {
37         return new FilterBuilder(this.resourcePrefix, this.filters + (this.filters && filterBuilder.filters ? "," : "") + filterBuilder.getFilters());
38     }
39
40     public getFilters() {
41         return this.filters;
42     }
43
44     public serialize() {
45         return "[" + this.filters + "]";
46     }
47
48     private addCondition(field: string, cond: string, value?: string | string[], prefix: string = "", postfix: string = "") {
49         if (value) {
50             value = typeof value === "string"
51                 ? `"${prefix}${value}${postfix}"`
52                 : `["${value.join(`","`)}"]`;
53
54             const resourcePrefix = this.resourcePrefix
55                 ? _.snakeCase(this.resourcePrefix) + "."
56                 : "";
57
58             this.filters += `${this.filters ? "," : ""}["${resourcePrefix}${_.snakeCase(field.toString())}","${cond}",${value}]`;
59         }
60         return this;
61     }
62 }