-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
930 lines (824 loc) · 32.3 KB
/
index.ts
File metadata and controls
930 lines (824 loc) · 32.3 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/**
* ObjectQL
* Copyright (c) 2026-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Redis Driver for ObjectQL (Example Implementation)
*
* This is a reference implementation demonstrating how to create a custom ObjectQL driver.
* It adapts Redis (a key-value store) to work with ObjectQL's universal data protocol.
*
* Implements both the legacy Driver interface from @objectql/types and
* the standard DriverInterface from @objectstack/spec for full compatibility
* with the new kernel-based plugin system.
*
* ⚠️ WARNING: This is an educational example, not production-ready.
* It uses full key scanning which is inefficient for large datasets.
*
* For production use, consider:
* - RedisJSON module for native JSON queries
* - RedisSearch for indexed queries
* - Secondary indexes using Redis Sets
*
* Note: This example implements only the core required methods from the Driver interface.
* Optional methods like introspectSchema(), aggregate(), transactions, etc. are not implemented.
*
* @version 4.0.0 - DriverInterface compliant
*/
import { Driver } from '@objectql/types';
import { DriverInterface, QueryAST, FilterNode, SortNode } from '@objectstack/spec';
import { createClient, RedisClientType } from 'redis';
/**
* Command interface for executeCommand method
*
* This interface defines the structure for all mutation operations
* (create, update, delete, and their bulk variants) in the v4.0 DriverInterface.
*
* @example
* // Create a single record
* const cmd: Command = { type: 'create', object: 'users', data: { name: 'Alice' } };
*
* @example
* // Update a record
* const cmd: Command = { type: 'update', object: 'users', id: '123', data: { email: 'new@example.com' } };
*
* @example
* // Bulk create multiple records
* const cmd: Command = {
* type: 'bulkCreate',
* object: 'users',
* records: [{ name: 'Alice' }, { name: 'Bob' }]
* };
*/
export interface Command {
/** Command type: create, update, delete, or their bulk variants */
type: 'create' | 'update' | 'delete' | 'bulkCreate' | 'bulkUpdate' | 'bulkDelete';
/** Target object name */
object: string;
/** Data for create/update operations */
data?: any;
/** Record ID for single update/delete operations */
id?: string | number;
/** Array of IDs for bulkDelete operation */
ids?: Array<string | number>;
/** Array of records for bulkCreate operation */
records?: any[];
/** Array of updates for bulkUpdate operation */
updates?: Array<{id: string | number, data: any}>;
/** Additional command-specific options */
options?: any;
}
/**
* Command result interface
*
* Standardized result format for all executeCommand operations.
*
* @example
* // Successful create
* { success: true, data: { id: '123', name: 'Alice' }, affected: 1 }
*
* @example
* // Failed operation
* { success: false, error: 'Record not found', affected: 0 }
*/
export interface CommandResult {
/** Whether the command executed successfully */
success: boolean;
/** The resulting data (for create/update operations) */
data?: any;
/** Number of records affected by the operation */
affected: number;
/** Error message if the command failed */
error?: string;
}
/**
* Configuration options for the Redis driver.
*/
export interface RedisDriverConfig {
/** Redis connection URL (e.g., 'redis://localhost:6379') */
url: string;
/** Additional Redis client options */
options?: any;
}
/**
* Redis Driver Implementation
*
* Stores ObjectQL documents as JSON strings in Redis with keys formatted as:
* `objectName:id`
*
* Example: `users:user-123` → `{"id":"user-123","name":"Alice",...}`
*/
export class RedisDriver implements Driver, DriverInterface {
// Driver metadata (ObjectStack-compatible)
public readonly name = 'RedisDriver';
public readonly version = '4.0.0';
public readonly supports = {
transactions: false,
joins: false,
fullTextSearch: false,
jsonFields: true,
arrayFields: true
};
private client: RedisClientType;
private config: RedisDriverConfig;
private connected: Promise<void>;
constructor(config: RedisDriverConfig) {
this.config = config;
this.client = createClient({
url: config.url,
...config.options
}) as RedisClientType;
// Handle connection errors
this.client.on('error', (err: Error) => {
console.error('[RedisDriver] Connection error:', err);
});
this.connected = this.connect();
}
async connect(): Promise<void> {
await this.client.connect();
}
/**
* Check database connection health
*/
async checkHealth(): Promise<boolean> {
try {
await this.connected;
await this.client.ping();
return true;
} catch (error) {
return false;
}
}
/**
* Find multiple records matching the query criteria.
*
* ⚠️ WARNING: This implementation scans ALL keys for the object type.
* Performance degrades with large datasets.
*/
async find(objectName: string, query: any = {}, options?: any): Promise<any[]> {
await this.connected;
// Normalize query to support both legacy and QueryAST formats
const normalizedQuery = this.normalizeQuery(query);
// Get all keys for this object type
const pattern = `${objectName}:*`;
const keys = await this.client.keys(pattern);
// Retrieve all documents
let results: any[] = [];
for (const key of keys) {
const data = await this.client.get(key);
if (data) {
try {
const doc = JSON.parse(data);
results.push(doc);
} catch (error) {
console.warn(`[RedisDriver] Failed to parse document at key ${key}:`, error);
}
}
}
// Apply filters (in-memory)
if (normalizedQuery.filters) {
results = this.applyFilters(results, normalizedQuery.filters);
}
// Apply sorting (in-memory)
if (normalizedQuery.sort && Array.isArray(normalizedQuery.sort)) {
results = this.applySort(results, normalizedQuery.sort);
}
// Apply pagination
if (normalizedQuery.skip) {
results = results.slice(normalizedQuery.skip);
}
if (normalizedQuery.limit) {
results = results.slice(0, normalizedQuery.limit);
}
// Apply field projection
if (normalizedQuery.fields && Array.isArray(normalizedQuery.fields)) {
results = results.map(doc => this.projectFields(doc, normalizedQuery.fields));
}
return results;
}
/**
* Find a single record by ID.
*/
async findOne(objectName: string, id: string | number, query?: any, options?: any): Promise<any> {
await this.connected;
// If ID is provided, fetch directly
if (id) {
const key = this.generateRedisKey(objectName, id);
const data = await this.client.get(key);
if (!data) {
return null;
}
try {
return JSON.parse(data);
} catch (error) {
console.warn(`[RedisDriver] Failed to parse document at key ${key}:`, error);
return null;
}
}
// If query is provided, use find and return first result
if (query) {
const results = await this.find(objectName, { ...query, limit: 1 }, options);
return results[0] || null;
}
return null;
}
/**
* Create a new record.
*/
async create(objectName: string, data: any, options?: any): Promise<any> {
await this.connected;
// Generate ID if not provided
const id = data.id || this.generateId();
const now = new Date().toISOString();
const doc = {
...data,
id,
created_at: data.created_at || now,
updated_at: data.updated_at || now
};
const key = this.generateRedisKey(objectName, id);
await this.client.set(key, JSON.stringify(doc));
return doc;
}
/**
* Update an existing record.
*/
async update(objectName: string, id: string | number, data: any, options?: any): Promise<any> {
await this.connected;
const key = this.generateRedisKey(objectName, id);
const existing = await this.client.get(key);
if (!existing) {
throw new Error(`Record not found: ${objectName}:${id}`);
}
const existingDoc = JSON.parse(existing);
const doc = {
...existingDoc,
...data,
id, // Preserve ID
created_at: existingDoc.created_at, // Preserve created_at
updated_at: new Date().toISOString()
};
await this.client.set(key, JSON.stringify(doc));
return doc;
}
/**
* Delete a record.
*/
async delete(objectName: string, id: string | number, options?: any): Promise<any> {
await this.connected;
const key = this.generateRedisKey(objectName, id);
const result = await this.client.del(key);
return result > 0;
}
/**
* Count records matching filters.
*
* ⚠️ WARNING: Loads all records to count matches.
*/
async count(objectName: string, filters: any, options?: any): Promise<number> {
await this.connected;
const pattern = `${objectName}:*`;
const keys = await this.client.keys(pattern);
// If no filters, return total count
if (!filters || (Array.isArray(filters) && filters.length === 0)) {
return keys.length;
}
// Extract actual filters from query object if needed
let actualFilters = filters;
if (filters && !Array.isArray(filters) && filters.filters) {
actualFilters = filters.filters;
}
// Count only records matching filters
let count = 0;
for (const key of keys) {
const data = await this.client.get(key);
if (data) {
try {
const doc = JSON.parse(data);
if (this.matchesFilters(doc, actualFilters)) {
count++;
}
} catch (error) {
console.warn(`[RedisDriver] Failed to parse document at key ${key}:`, error);
}
}
}
return count;
}
/**
* Close the Redis connection.
*/
async disconnect(): Promise<void> {
await this.client.quit();
}
/**
* Execute a query (DriverInterface v4.0 method)
*
* This method handles all read operations using the QueryAST format from @objectstack/spec.
* It provides a standardized query interface that supports:
* - Field selection (projection)
* - Filter conditions (using FilterNode AST)
* - Sorting
* - Pagination (skip/top)
* - Grouping and aggregations (delegated to find)
*
* The method converts the QueryAST format to the legacy query format and delegates
* to the existing find() method for backward compatibility.
*
* @param ast - The query Abstract Syntax Tree
* @param options - Optional execution options
* @returns Object containing query results and count
*
* @example
* // Simple query
* const result = await driver.executeQuery({
* object: 'users',
* fields: ['name', 'email']
* });
*
* @example
* // Query with filters and sorting
* const result = await driver.executeQuery({
* object: 'users',
* filters: {
* type: 'comparison',
* field: 'age',
* operator: '>',
* value: 18
* },
* sort: [{ field: 'name', order: 'asc' }],
* top: 10
* });
*/
async executeQuery(ast: QueryAST, options?: any): Promise<{ value: any[]; count?: number }> {
const objectName = ast.object || '';
// Convert QueryAST to legacy query format
const legacyQuery: any = {
fields: ast.fields,
filters: this.convertFilterNodeToLegacy(ast.filters),
sort: ast.sort?.map((s: SortNode) => [s.field, s.order]),
limit: ast.top,
skip: ast.skip,
};
// Use existing find method
const results = await this.find(objectName, legacyQuery, options);
return {
value: results,
count: results.length
};
}
/**
* Execute a command (DriverInterface v4.0 method)
*
* This method provides a unified interface for all mutation operations (create, update, delete)
* using the Command pattern from @objectstack/spec.
*
* Supports both single operations and bulk operations:
* - Single: create, update, delete
* - Bulk: bulkCreate, bulkUpdate, bulkDelete
*
* Bulk operations use Redis PIPELINE for optimal performance, executing multiple
* commands in a single round-trip to the server.
*
* All operations return a standardized CommandResult with:
* - success: boolean indicating operation success/failure
* - data: the resulting data (for create/update)
* - affected: number of records affected
* - error: error message if operation failed
*
* @param command - The command to execute (see Command interface)
* @param options - Optional execution options
* @returns Standardized command execution result
*
* @example
* // Create a single record
* const result = await driver.executeCommand({
* type: 'create',
* object: 'users',
* data: { name: 'Alice', email: 'alice@example.com' }
* });
*
* @example
* // Bulk create multiple records
* const result = await driver.executeCommand({
* type: 'bulkCreate',
* object: 'users',
* records: [
* { name: 'Alice' },
* { name: 'Bob' },
* { name: 'Charlie' }
* ]
* });
*
* @example
* // Update a record
* const result = await driver.executeCommand({
* type: 'update',
* object: 'users',
* id: 'user-123',
* data: { email: 'newemail@example.com' }
* });
*/
async executeCommand(command: Command, options?: any): Promise<CommandResult> {
try {
await this.connected;
const cmdOptions = { ...options, ...command.options };
switch (command.type) {
case 'create':
if (!command.data) {
throw new Error('Create command requires data');
}
const created = await this.create(command.object, command.data, cmdOptions);
return {
success: true,
data: created,
affected: 1
};
case 'update':
if (!command.id || !command.data) {
throw new Error('Update command requires id and data');
}
const updated = await this.update(command.object, command.id, command.data, cmdOptions);
return {
success: true,
data: updated,
affected: 1
};
case 'delete':
if (!command.id) {
throw new Error('Delete command requires id');
}
await this.delete(command.object, command.id, cmdOptions);
return {
success: true,
affected: 1
};
case 'bulkCreate':
if (!command.records || !Array.isArray(command.records)) {
throw new Error('BulkCreate command requires records array');
}
// Use Redis PIPELINE for batch operations
const pipeline = this.client.multi();
const bulkCreated: any[] = [];
const now = new Date().toISOString();
for (const record of command.records) {
const id = record.id || this.generateId();
const doc = {
...record,
id,
created_at: record.created_at || now,
updated_at: record.updated_at || now
};
bulkCreated.push(doc);
const key = this.generateRedisKey(command.object, id);
pipeline.set(key, JSON.stringify(doc));
}
await pipeline.exec();
return {
success: true,
data: bulkCreated,
affected: command.records.length
};
case 'bulkUpdate':
if (!command.updates || !Array.isArray(command.updates)) {
throw new Error('BulkUpdate command requires updates array');
}
// First, batch GET all existing records using PIPELINE
const getPipeline = this.client.multi();
for (const update of command.updates) {
const key = this.generateRedisKey(command.object, update.id);
getPipeline.get(key);
}
const getResults = await getPipeline.exec();
// Then, batch SET updated records using PIPELINE
const setPipeline = this.client.multi();
const updateResults: any[] = [];
const updateTime = new Date().toISOString();
for (let i = 0; i < command.updates.length; i++) {
const update = command.updates[i];
// Redis v4 client returns array of results directly, not [error, result] tuples
const existingData = getResults?.[i];
if (existingData && typeof existingData === 'string') {
const existingDoc = JSON.parse(existingData);
const doc = {
...existingDoc,
...update.data,
id: update.id,
created_at: existingDoc.created_at,
updated_at: updateTime
};
updateResults.push(doc);
const key = this.generateRedisKey(command.object, update.id);
setPipeline.set(key, JSON.stringify(doc));
}
}
// Only execute pipeline if there are commands to execute
if (updateResults.length > 0) {
await setPipeline.exec();
}
return {
success: true,
data: updateResults,
affected: updateResults.length
};
case 'bulkDelete':
if (!command.ids || !Array.isArray(command.ids)) {
throw new Error('BulkDelete command requires ids array');
}
// Use Redis PIPELINE for batch operations
const deletePipeline = this.client.multi();
for (const id of command.ids) {
const key = this.generateRedisKey(command.object, id);
deletePipeline.del(key);
}
const deleteResults = await deletePipeline.exec();
// Redis v4 client returns array of results directly, not [error, result] tuples
// Each DEL returns 1 if key existed and was deleted, 0 if key didn't exist
const deleted = deleteResults?.filter((r: any) => r > 0).length || 0;
return {
success: true,
affected: deleted
};
default:
throw new Error(`Unknown command type: ${(command as any).type}`);
}
} catch (error: any) {
return {
success: false,
error: error.message || 'Command execution failed',
affected: 0
};
}
}
// ========== Helper Methods ==========
/**
* Convert FilterNode (QueryAST format) to legacy filter array format
*
* This method bridges the gap between the new QueryAST filter format (tree-based)
* and the legacy array-based filter format used internally by the driver.
*
* QueryAST FilterNode format:
* - type: 'comparison' | 'and' | 'or' | 'not'
* - field, operator, value for comparisons
* - children for logical operators
*
* Legacy format:
* - Array of conditions: [field, operator, value]
* - String separators: 'and', 'or'
* - Example: [['age', '>', 18], 'and', ['role', '=', 'user']]
*
* @param node - The FilterNode to convert
* @returns Legacy filter array format, or undefined if no filters
* @private
*
* @example
* // Input: { type: 'comparison', field: 'age', operator: '>', value: 18 }
* // Output: [['age', '>', 18]]
*
* @example
* // Input: { type: 'and', children: [...] }
* // Output: [['field1', '=', 'val1'], 'and', ['field2', '>', 10]]
*/
private convertFilterNodeToLegacy(node?: FilterNode): any {
if (!node) return undefined;
switch (node.type) {
case 'comparison':
// Convert comparison node to [field, operator, value] format
if (!node.operator) {
console.warn('[RedisDriver] FilterNode comparison missing operator, defaulting to "="');
}
const operator = node.operator || '=';
return [[node.field, operator, node.value]];
case 'and':
// Convert AND node to array with 'and' separator
if (!node.children || node.children.length === 0) return undefined;
const andResults: any[] = [];
for (const child of node.children) {
const converted = this.convertFilterNodeToLegacy(child);
if (converted) {
if (andResults.length > 0) {
andResults.push('and');
}
andResults.push(...(Array.isArray(converted) ? converted : [converted]));
}
}
return andResults.length > 0 ? andResults : undefined;
case 'or':
// Convert OR node to array with 'or' separator
if (!node.children || node.children.length === 0) return undefined;
const orResults: any[] = [];
for (const child of node.children) {
const converted = this.convertFilterNodeToLegacy(child);
if (converted) {
if (orResults.length > 0) {
orResults.push('or');
}
orResults.push(...(Array.isArray(converted) ? converted : [converted]));
}
}
return orResults.length > 0 ? orResults : undefined;
case 'not':
// NOT is not directly supported in legacy format
// We could implement it by negating the child operators
console.warn('[RedisDriver] NOT operator in filters is not fully supported in legacy format');
return undefined;
default:
return undefined;
}
}
/**
* Generate Redis key for an object record
*
* This method implements the key naming strategy for storing records in Redis.
* The strategy uses a simple pattern: `objectName:id`
*
* This ensures:
* - Easy querying by pattern (e.g., `users:*` to find all user records)
* - Clear namespace separation between different object types
* - Human-readable keys for debugging
*
* @param objectName - The object/collection name
* @param id - The record ID
* @returns Redis key in format "objectName:id"
* @private
*
* @example
* generateRedisKey('users', '123') // Returns: 'users:123'
* generateRedisKey('orders', 'order-456') // Returns: 'orders:order-456'
*/
private generateRedisKey(objectName: string, id: string | number): string {
return `${objectName}:${id}`;
}
/**
* Normalizes query format to support both legacy UnifiedQuery and QueryAST formats.
* This ensures backward compatibility while supporting the new @objectstack/spec interface.
*
* QueryAST format uses 'top' for limit, while UnifiedQuery uses 'limit'.
* QueryAST sort is array of {field, order}, while UnifiedQuery is array of [field, order].
*/
private normalizeQuery(query: any): any {
if (!query) return {};
const normalized: any = { ...query };
// Normalize limit/top
if (normalized.top !== undefined && normalized.limit === undefined) {
normalized.limit = normalized.top;
}
// Normalize sort format
if (normalized.sort && Array.isArray(normalized.sort)) {
// Check if it's already in the array format [field, order]
const firstSort = normalized.sort[0];
if (firstSort && typeof firstSort === 'object' && !Array.isArray(firstSort)) {
// Convert from QueryAST format {field, order} to internal format [field, order]
normalized.sort = normalized.sort.map((item: any) => [
item.field,
item.order || item.direction || item.dir || 'asc'
]);
}
}
return normalized;
}
/**
* Apply filters to an array of records (in-memory filtering).
*
* Supports ObjectQL filter format:
* [
* ['field', 'operator', value],
* 'or',
* ['field2', 'operator', value2]
* ]
*/
private applyFilters(records: any[], filters: any[]): any[] {
if (!filters || filters.length === 0) {
return records;
}
return records.filter(record => this.matchesFilters(record, filters));
}
/**
* Check if a single record matches the filter conditions.
*/
private matchesFilters(record: any, filters: any[]): boolean {
if (!filters || filters.length === 0) {
return true;
}
let conditions: boolean[] = [];
let operators: string[] = [];
for (const item of filters) {
if (typeof item === 'string') {
// Logical operator (and/or)
operators.push(item.toLowerCase());
} else if (Array.isArray(item)) {
const [field, operator, value] = item;
// Handle nested filter groups
if (typeof field !== 'string') {
// Nested group - recursively evaluate
conditions.push(this.matchesFilters(record, item));
} else {
// Single condition
const matches = this.evaluateCondition(record[field], operator, value);
conditions.push(matches);
}
}
}
// Combine conditions with operators
if (conditions.length === 0) {
return true;
}
let result = conditions[0];
for (let i = 0; i < operators.length; i++) {
const op = operators[i];
const nextCondition = conditions[i + 1];
if (op === 'or') {
result = result || nextCondition;
} else { // 'and' or default
result = result && nextCondition;
}
}
return result;
}
/**
* Evaluate a single filter condition.
*/
private evaluateCondition(fieldValue: any, operator: string, compareValue: any): boolean {
switch (operator) {
case '=':
return fieldValue === compareValue;
case '!=':
return fieldValue !== compareValue;
case '>':
return fieldValue > compareValue;
case '>=':
return fieldValue >= compareValue;
case '<':
return fieldValue < compareValue;
case '<=':
return fieldValue <= compareValue;
case 'in':
return Array.isArray(compareValue) && compareValue.includes(fieldValue);
case 'nin':
return Array.isArray(compareValue) && !compareValue.includes(fieldValue);
case 'contains':
return String(fieldValue).toLowerCase().includes(String(compareValue).toLowerCase());
default:
console.warn(`[RedisDriver] Unsupported operator: ${operator}`);
return false;
}
}
/**
* Apply sorting to an array of records (in-memory sorting).
*/
private applySort(records: any[], sort: any[]): any[] {
const sorted = [...records];
// Apply sorts in reverse order for correct precedence
for (let i = sort.length - 1; i >= 0; i--) {
const sortItem = sort[i];
let field: string;
let direction: string;
if (Array.isArray(sortItem)) {
[field, direction] = sortItem;
} else if (typeof sortItem === 'object') {
field = sortItem.field;
direction = sortItem.order || sortItem.direction || sortItem.dir || 'asc';
} else {
continue;
}
sorted.sort((a, b) => {
const aVal = a[field];
const bVal = b[field];
// Handle null/undefined
if (aVal == null && bVal == null) return 0;
if (aVal == null) return 1;
if (bVal == null) return -1;
// Compare values
if (aVal < bVal) return direction === 'asc' ? -1 : 1;
if (aVal > bVal) return direction === 'asc' ? 1 : -1;
return 0;
});
}
return sorted;
}
/**
* Project specific fields from a document.
*/
private projectFields(doc: any, fields: string[]): any {
const result: any = {};
for (const field of fields) {
if (doc[field] !== undefined) {
result[field] = doc[field];
}
}
return result;
}
/**
* Generate a unique ID (simple UUID v4 implementation).
*/
private generateId(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}