1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as _ from "lodash";
6 import { Resource } from "./common-resource-service";
8 export default class FilterBuilder<T extends Resource = Resource> {
10 static create<T extends Resource = Resource>(resourcePrefix = "") {
11 return new FilterBuilder<T>(resourcePrefix);
15 private resourcePrefix = "",
16 private filters = "") { }
18 public addEqual(field: keyof T, value?: string) {
19 return this.addCondition(field, "=", value);
22 public addLike(field: keyof T, value?: string) {
23 return this.addCondition(field, "like", value, "%", "%");
26 public addILike(field: keyof T, value?: string) {
27 return this.addCondition(field, "ilike", value, "%", "%");
30 public addIsA(field: keyof T, value?: string | string[]) {
31 return this.addCondition(field, "is_a", value);
34 public addIn(field: keyof T, value?: string | string[]) {
35 return this.addCondition(field, "in", value);
38 public concat<O extends Resource>(filterBuilder: FilterBuilder<O>) {
39 return new FilterBuilder(this.resourcePrefix, this.filters + (this.filters && filterBuilder.filters ? "," : "") + filterBuilder.getFilters());
47 return "[" + this.filters + "]";
50 private addCondition(field: keyof T, cond: string, value?: string | string[], prefix: string = "", postfix: string = "") {
52 value = typeof value === "string"
53 ? `"${prefix}${value}${postfix}"`
54 : `["${value.join(`","`)}"]`;
56 const resourcePrefix = this.resourcePrefix
57 ? _.snakeCase(this.resourcePrefix) + "."
60 this.filters += `${this.filters ? "," : ""}["${resourcePrefix}${_.snakeCase(field.toString())}","${cond}",${value}]`;