Untitled
import { ODataConfig } from "./odata/odata-config"; import { ODataSort } from "./odata/odata-sort"; import { ODataSortingDirection } from "./odata/sorting-direction"; import { BaseODataFilter } from "./odata/base-odata-filter"; import { WithIndexer } from "../types/with-indexer"; import { createError } from "../exceptions/exception-factory"; import { tryGetObjectFromCoreCache, setCoreCache } from "../caching/core-memory-cache"; import { FdMemoryCacheOptions } from "../caching/fd-memory-cache-options"; import { getUserId } from "../auth/users/current-user-id-provider"; import { Uuid } from "../types/uuid"; export class ODataExpressionOperationsService { constructor(private db: any) {} sort(query: any, oDataConfig: ODataConfig) { const sortedConfigs = oDataConfig.Sorts.sort((a, b) => b.Priority - a.Priority); let dynamicQuery = query.$dynamic(); for (const sort of sortedConfigs) { const methodName = sort.Direction === ODataSortingDirection.Ascending ? 'orderBy' : 'orderByDesc'; dynamicQuery = dynamicQuery[methodName](sort.PropertyName); } return dynamicQuery; } skip(query: any, value: number) { return query.offset(value); } take(query: any, value: number) { return query.limit(value); } select(query: any, oDataConfig: ODataConfig) { const tableName = query.getTableName(); // Assuming this method exists const tableColumns = this.db[tableName]; // Get table columns const selectProperties = Object.keys(oDataConfig.Selects) .filter(select => tableColumns[select]) .map(select => tableColumns[select]); return query.select(...selectProperties); } applyFilters(query: any, filters: BaseODataFilter[]) { let dynamicQuery = query.$dynamic(); for (const filter of filters) { // Implement filter logic based on your ODataFilterType and ODataComparisonType // This is a simplified example dynamicQuery = dynamicQuery.where(eq(filter.LeftSide, filter.RightSide)); } return dynamicQuery; } } // Helper function for pagination export function withPagination<T extends any>( qb: T, page: number = 1, pageSize: number = 10, ) { return qb.limit(pageSize).offset((page - 1) * pageSize); } // Example usage const oDataService = new ODataExpressionOperationsService(db); let query = db.select().from(users).where(eq(users.id, getUserId())).$dynamic(); // Apply sorting query = oDataService.sort(query, { Sorts: [{ PropertyName: 'name', Direction: ODataSortingDirection.Ascending, Priority: 1 }] }); // Apply pagination query = withPagination(query, 2, 20); // Apply field selection query = oDataService.select(query, { Selects: { name: [], email: [] } }); // Apply filters query = oDataService.applyFilters(query, [ { LeftSide: 'status', RightSide: 'active', ComparisonType: ODataComparisonType.Equal, Type: ODataFilterType.Default, LogicalOperationType: ODataLogicalOperationType.And } ]); // Execute query const result = await query;
Leave a Comment