summaryrefslogtreecommitdiff
path: root/components/client-table-v2/adapter/create-table-service.ts
blob: 41c38906dea92fa3b612df61fd847d18745fd15c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { PgTable } from "drizzle-orm/pg-core";
import { DrizzleTableAdapter, DrizzleTableState } from "./drizzle-table-adapter";
import { ColumnDef } from "@tanstack/react-table";
import { SQL, and, count } from "drizzle-orm";

// Define a minimal DB interface that we need
// Adjust this to match your actual db instance type
interface DbInstance {
  select: (args?: any) => any;
}

export interface CreateTableServiceConfig<TData> {
  /**
   * Drizzle Database Instance
   */
  db: DbInstance;
  
  /**
   * Drizzle Table Schema (e.g. users, orders)
   */
  schema: PgTable; // Using PgTable as base, works for most Drizzle tables
  
  /**
   * React Table Columns Definition
   * Used to map accessorKeys to DB columns
   */
  columns: ColumnDef<TData, any>[];
  
  /**
   * Optional: Custom WHERE clause to always apply (e.g. deleted_at IS NULL)
   */
  defaultWhere?: SQL;
  
  /**
   * Optional: Custom query modifier
   * Allows joining other tables or selecting specific fields
   */
  customQuery?: (queryBuilder: any) => any;
}

/**
 * Factory function to create a standardized server action for a table.
 * 
 * @example
 * export const getUsers = createTableService({
 *   db,
 *   schema: users,
 *   columns: userColumns
 * });
 */
export function createTableService<TData>(config: CreateTableServiceConfig<TData>) {
  const { db, schema, columns, defaultWhere, customQuery } = config;

  // Return the actual Server Action function
  return async function getTableData(tableState: DrizzleTableState) {
    const adapter = new DrizzleTableAdapter(schema, columns);
    const { where, orderBy, limit, offset, groupBy } = adapter.getQueryParts(tableState);

    // Merge defaultWhere with dynamic where
    const finalWhere = defaultWhere 
      ? (where ? and(defaultWhere, where) : defaultWhere) 
      : where;

    // 1. Build Data Query
    let dataQuery = db.select()
      .from(schema)
      .where(finalWhere)
      .orderBy(...orderBy)
      .limit(limit)
      .offset(offset);

    if (groupBy && groupBy.length > 0) {
      dataQuery = dataQuery.groupBy(...groupBy);
    }

    // Apply custom query modifications (joins, etc)
    if (customQuery) {
      dataQuery = customQuery(dataQuery);
    }

    // 2. Build Count Query
    const countQuery = db.select({ count: count() })
      .from(schema)
      .where(finalWhere);

    // Execute queries
    // We use Promise.all to run them in parallel
    const [data, countResult] = await Promise.all([
      dataQuery,
      countQuery
    ]);

    const totalRows = Number(countResult[0]?.count ?? 0);

    return {
      data: data as TData[],
      totalRows,
      pageCount: Math.ceil(totalRows / (tableState.pagination?.pageSize ?? 10))
    };
  };
}