Add convenience create method add handle Resource type in FitlerBuilder
[arvados-workbench2.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 import { Resource } from "./common-resource-service";
7
8 export default class FilterBuilder<T extends Resource = Resource> {
9     private filters = "";
10
11     static create<T extends Resource = Resource>() {
12         return new FilterBuilder<T>();
13     }
14
15     private addCondition(field: keyof T, cond: string, value?: string | string[], prefix: string = "", postfix: string = "") {
16         if (value) {
17             value = typeof value === "string"
18                 ? `"${prefix}${value}${postfix}"`
19                 : `["${value.join(`","`)}"]`;
20
21             this.filters += `["${_.snakeCase(field.toString())}","${cond}",${value}]`;
22         }
23         return this;
24     }
25
26     public addEqual(field: keyof T, value?: string) {
27         return this.addCondition(field, "=", value);
28     }
29
30     public addLike(field: keyof T, value?: string) {
31         return this.addCondition(field, "like", value, "", "%");
32     }
33
34     public addILike(field: keyof T, value?: string) {
35         return this.addCondition(field, "ilike", value, "", "%");
36     }
37
38     public addIsA(field: keyof T, value?: string | string[]) {
39         return this.addCondition(field, "is_a", value);
40     }
41
42     public get() {
43         return "[" + this.filters + "]";
44     }
45 }