// SPDX-License-Identifier: AGPL-3.0
import * as _ from "lodash";
-import { Resource } from "./common-resource-service";
-export default class FilterBuilder<T extends Resource = Resource> {
- private filters = "";
+export class FilterBuilder {
+ static create(resourcePrefix = "") {
+ return new FilterBuilder(resourcePrefix);
+ }
+
+ constructor(
+ private resourcePrefix = "",
+ private filters = "") { }
- static create<T extends Resource = Resource>() {
- return new FilterBuilder<T>();
+ public addEqual(field: string, value?: string) {
+ return this.addCondition(field, "=", value);
}
- private addCondition(field: keyof T, cond: string, value?: string | string[], prefix: string = "", postfix: string = "") {
- if (value) {
- value = typeof value === "string"
- ? `"${prefix}${value}${postfix}"`
- : `["${value.join(`","`)}"]`;
+ public addLike(field: string, value?: string) {
+ return this.addCondition(field, "like", value, "%", "%");
+ }
- this.filters += `["${_.snakeCase(field.toString())}","${cond}",${value}]`;
- }
- return this;
+ public addILike(field: string, value?: string) {
+ return this.addCondition(field, "ilike", value, "%", "%");
}
- public addEqual(field: keyof T, value?: string) {
- return this.addCondition(field, "=", value);
+ public addIsA(field: string, value?: string | string[]) {
+ return this.addCondition(field, "is_a", value);
}
- public addLike(field: keyof T, value?: string) {
- return this.addCondition(field, "like", value, "", "%");
+ public addIn(field: string, value?: string | string[]) {
+ return this.addCondition(field, "in", value);
}
- public addILike(field: keyof T, value?: string) {
- return this.addCondition(field, "ilike", value, "", "%");
+ public concat(filterBuilder: FilterBuilder) {
+ return new FilterBuilder(this.resourcePrefix, this.filters + (this.filters && filterBuilder.filters ? "," : "") + filterBuilder.getFilters());
}
- public addIsA(field: keyof T, value?: string | string[]) {
- return this.addCondition(field, "is_a", value);
+ public getFilters() {
+ return this.filters;
}
- public get() {
+ public serialize() {
return "[" + this.filters + "]";
}
+
+ private addCondition(field: string, cond: string, value?: string | string[], prefix: string = "", postfix: string = "") {
+ if (value) {
+ value = typeof value === "string"
+ ? `"${prefix}${value}${postfix}"`
+ : `["${value.join(`","`)}"]`;
+
+ const resourcePrefix = this.resourcePrefix
+ ? _.snakeCase(this.resourcePrefix) + "."
+ : "";
+
+ this.filters += `${this.filters ? "," : ""}["${resourcePrefix}${_.snakeCase(field.toString())}","${cond}",${value}]`;
+ }
+ return this;
+ }
}