Simplify order and filter builder
[arvados.git] / src / common / api / order-builder.ts
index cc3eadbb904ffb947c34121f8852a35fab256b18..196b06952e55c911d9cd0bac6ed881151918bf98 100644 (file)
@@ -2,21 +2,29 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
+import * as _ from "lodash";
+import { Resource } from "~/models/resource";
 
-export default class OrderBuilder {
-    private order: string[] = [];
+export enum OrderDirection { ASC, DESC }
 
-    addAsc(attribute: string) {
-        this.order.push(`${attribute} asc`);
+export class OrderBuilder<T extends Resource = Resource> {
+
+    constructor(private order: string[] = []) {}
+
+    addOrder(direction: OrderDirection, attribute: keyof T, prefix?: string) {
+        this.order.push(`${prefix ? prefix + "." : ""}${_.snakeCase(attribute.toString())} ${direction === OrderDirection.ASC ? "asc" : "desc"}`);
         return this;
     }
 
-    addDesc(attribute: string) {
-        this.order.push(`${attribute} desc`);
-        return this;
+    addAsc(attribute: keyof T, prefix?: string) {
+        return this.addOrder(OrderDirection.ASC, attribute, prefix);
+    }
+
+    addDesc(attribute: keyof T, prefix?: string) {
+        return this.addOrder(OrderDirection.DESC, attribute, prefix);
     }
 
-    get() {
-        return this.order;
+    getOrder() {
+        return this.order.join(",");
     }
 }