Compare commits

...

8 Commits

Author SHA1 Message Date
7fab4e5dd0 5.16.4
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Successful in 3m12s
Default (tags) / release (push) Failing after 1m0s
Default (tags) / metadata (push) Successful in 1m11s
2025-08-18 20:24:16 +00:00
0dbaa1bc5d fix(classes.doc (convertFilterForMongoDb)): Improve filter conversion: handle logical operators, merge operator objects, add nested filter tests and docs, and fix test script 2025-08-18 20:24:16 +00:00
8b37ebc8f9 5.16.3
Some checks failed
Default (tags) / security (push) Successful in 1m10s
Default (tags) / test (push) Successful in 3m14s
Default (tags) / release (push) Failing after 1m2s
Default (tags) / metadata (push) Successful in 1m15s
2025-08-18 19:38:44 +00:00
5d757207c8 fix(docs): Add local Claude settings and remove outdated codex.md 2025-08-18 19:38:44 +00:00
c80df05fdf 5.16.2
Some checks failed
Default (tags) / security (push) Successful in 51s
Default (tags) / test (push) Successful in 3m16s
Default (tags) / release (push) Failing after 5m2s
Default (tags) / metadata (push) Successful in 7m2s
2025-08-18 11:50:37 +00:00
9be43a85ef fix(readme): Update README: clarify examples, expand search/cursor/docs and add local Claude settings 2025-08-18 11:50:37 +00:00
bf66209d3e feat: Enhance type safety for MongoDB filter conditions by introducing helper types for $in and $nin values 2025-08-18 11:42:41 +00:00
cdd1ae2c9b feat: Add comprehensive query filters guide and enhance type safety for MongoDB queries
- Introduced a detailed guide on query filters in the README, covering basic filtering, comparison operators, array operators, logical operators, element operators, and advanced filtering patterns.
- Implemented a type-safe filtering system in `classes.doc.ts` with `MongoFilterCondition` and `MongoFilter` types to support MongoDB operators while maintaining nested type safety.
- Enhanced error handling for invalid operators and conditions in the filtering logic.
- Added extensive tests for various filtering scenarios, including basic, comparison, array, logical, and complex filters, ensuring robust functionality and performance.
- Implemented security measures to prevent the use of dangerous operators like `$where` and validate operator usage.
2025-08-18 11:29:15 +00:00
8 changed files with 2542 additions and 1197 deletions

View File

@@ -1,5 +1,30 @@
# Changelog
## 2025-08-18 - 5.16.4 - fix(classes.doc (convertFilterForMongoDb))
Improve filter conversion: handle logical operators, merge operator objects, add nested filter tests and docs, and fix test script
- Fix package.json test script: remove stray dot in tstest --verbose argument to ensure tests run correctly
- Enhance convertFilterForMongoDb in ts/classes.doc.ts to properly handle logical operators ($and, $or, $nor, $not) and return them recursively
- Merge operator objects for the same field path (e.g. combining $gte and $lte) to avoid overwriting operator clauses when object and dot-notation are mixed
- Add validation/guards for operator argument types (e.g. $in, $nin, $all must be arrays; $size must be numeric) and preserve existing behavior blocking $where for security
- Add comprehensive nested filter tests in test/test.filters.ts to cover deep nested object queries, $elemMatch, array size, $all, $in on nested fields and more
- Expand README filtering section with detailed examples for basic filtering, deep nested filters, comparison operators, array operations, logical and element operators, and advanced patterns
## 2025-08-18 - 5.16.3 - fix(docs)
Add local Claude settings and remove outdated codex.md
- Added .claude/settings.local.json to store local Claude/assistant permissions and configuration.
- Removed codex.md (project overview) — documentation file deleted.
- No runtime/library code changes; documentation/configuration-only update, bump patch version.
## 2025-08-18 - 5.16.2 - fix(readme)
Update README: clarify examples, expand search/cursor/docs and add local Claude settings
- Refined README wording and structure: clearer Quick Start, improved examples and developer-focused phrasing
- Expanded documentation for search, cursors, change streams, distributed coordination, transactions and EasyStore with more concrete code examples
- Adjusted code examples to show safer defaults (ID generation, status/tags, connection pooling) and improved best-practices guidance
- Added .claude/settings.local.json to provide local assistant/CI permission configuration
## 2025-08-12 - 5.16.1 - fix(core)
Improve error handling and logging; enhance search query sanitization; update dependency versions and documentation

View File

@@ -1,77 +0,0 @@
# SmartData Project Overview
This document provides a high-level overview of the SmartData library (`@push.rocks/smartdata`), its architecture, core components, and key features—including recent enhancements to the search API.
## 1. Project Purpose
- A TypeScriptfirst wrapper around MongoDB that supplies:
- Stronglytyped document & collection classes
- Decoratorbased schema definition (no external schema files)
- Advanced search capabilities with Lucenestyle queries
- Builtin support for realtime data sync, distributed coordination, and keyvalue EasyStore
## 2. Core Concepts & Components
- **SmartDataDb**: Manages the MongoDB connection, pooling, and initialization of collections.
- **SmartDataDbDoc**: Base class for all document models; provides CRUD, upsert, and cursor APIs.
- **Decorators**:
- `@Collection`: Associates a class with a MongoDB collection
- `@svDb()`: Marks a field as persisted to the DB
- `@unI()`: Marks a field as a unique index
- `@index()`: Adds a regular index
- `@searchable()`: Marks a field for inclusion in text searches or regex queries
- **SmartdataCollection**: Wraps a MongoDB collection; autocreates indexes based on decorators.
- **Lucene Adapter**: Parses a Lucene query string into an AST and transforms it to a MongoDB filter object.
- **EasyStore**: A simple, schemaless keyvalue store built on top of MongoDB for sharing ephemeral data.
- **Distributed Coordinator**: Leader election and taskdistribution API for building resilient, multiinstance systems.
- **Watcher**: Listens to change streams for realtime updates and integrates with RxJS.
## 3. Search API
SmartData provides a unified `.search(query[, opts])` method on all models with `@searchable()` fields:
- **Supported Syntax**:
1. Exact field:value (e.g. `field:Value`)
2. Quoted phrases (e.g. `"exact phrase"` or `'exact phrase'`)
3. Wildcards: `*` (zero or more chars) and `?` (single char)
4. Boolean operators: `AND`, `OR`, `NOT`
5. Grouping: parenthesis `(A OR B) AND C`
6. Range queries: `[num TO num]`, `{num TO num}`
7. Multiterm unquoted: terms ANDd across all searchable fields
8. Empty query returns all documents
- **Fallback Mechanisms**:
1. Text index based `$text` search (if supported)
2. Fieldscoped and multifield regex queries
3. Inmemory filtering for complex or unsupported cases
### New Security & Extensibility Hooks
The `.search(query, opts?)` signature now accepts a `SearchOptions<T>` object:
```ts
interface SearchOptions<T> {
filter?: Record<string, any>; // Additional MongoDB filter ANDmerged
validate?: (doc: T) => boolean; // Postfetch hook to drop results
}
```
- **filter**: Enforces mandatory constraints (e.g. multitenant isolation) directly in the Mongo query.
- **validate**: An async function that runs after fetching; return `false` to exclude a document.
## 4. Testing Strategy
- Unit tests in `test/test.search.ts` cover basic search functionality and new options:
- Exact, wildcard, phrase, boolean and grouping cases
- Implicit AND and mixed freeterm + field searches
- Edge cases (nonsearchable fields, quoted wildcards, no matches)
- `filter` and `validate` tests ensure security hooks work as intended
- Advanced search scenarios are covered in `test/test.search.advanced.ts`.
## 5. Usage Example
```ts
// Basic search
const prods = await Product.search('wireless earbuds');
// Scoped search (only your organizations items)
const myItems = await Product.search('book', { filter: { ownerId } });
// Postsearch validation (only cheap items)
const cheapItems = await Product.search('', { validate: p => p.price < 50 });
```
---
Last updated: 2025-04-22

View File

@@ -1,13 +1,13 @@
{
"name": "@push.rocks/smartdata",
"version": "5.16.1",
"version": "5.16.4",
"private": false,
"description": "An advanced library for NoSQL data organization and manipulation using TypeScript with support for MongoDB, data validation, collections, and custom data types.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "tstest test/ --verbose",
"test": "tstest test/ --verbose --logfile --timeout 120",
"testSearch": "tsx test/test.search.ts",
"build": "tsbuild --web --allowimplicitany",
"buildDocs": "tsdoc"
@@ -37,10 +37,10 @@
"mongodb": "^6.18.0"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.6.4",
"@git.zone/tsbuild": "^2.6.7",
"@git.zone/tsrun": "^1.2.44",
"@git.zone/tstest": "^2.3.2",
"@push.rocks/qenv": "^6.0.5",
"@git.zone/tstest": "^2.3.5",
"@push.rocks/qenv": "^6.1.3",
"@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^22.15.2"
},

1766
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

877
readme.md

File diff suppressed because it is too large Load Diff

819
test/test.filters.ts Normal file
View File

@@ -0,0 +1,819 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartmongo from '@push.rocks/smartmongo';
import * as smartunique from '@push.rocks/smartunique';
import * as smartdata from '../ts/index.js';
const { SmartdataDb, Collection, svDb, unI, index } = smartdata;
let smartmongoInstance: smartmongo.SmartMongo;
let testDb: smartdata.SmartdataDb;
// Define test document classes
@Collection(() => testDb)
class TestUser extends smartdata.SmartDataDbDoc<TestUser, TestUser> {
@unI()
public id: string = smartunique.shortId();
@svDb()
public name: string;
@svDb()
public age: number;
@svDb()
public email: string;
@svDb()
public roles: string[];
@svDb()
public tags: string[];
@svDb()
public status: 'active' | 'inactive' | 'pending';
@svDb()
public metadata: {
lastLogin?: Date;
loginCount?: number;
preferences?: Record<string, any>;
};
@svDb()
public scores: number[];
constructor(data: Partial<TestUser> = {}) {
super();
Object.assign(this, data);
}
}
@Collection(() => testDb)
class TestOrder extends smartdata.SmartDataDbDoc<TestOrder, TestOrder> {
@unI()
public id: string = smartunique.shortId();
@svDb()
public userId: string;
@svDb()
public items: Array<{
product: string;
quantity: number;
price: number;
}>;
@svDb()
public totalAmount: number;
@svDb()
public status: string;
@svDb()
public tags: string[];
constructor(data: Partial<TestOrder> = {}) {
super();
Object.assign(this, data);
}
}
// Setup and teardown
tap.test('should create a test database instance', async () => {
smartmongoInstance = await smartmongo.SmartMongo.createAndStart();
testDb = new smartdata.SmartdataDb(await smartmongoInstance.getMongoDescriptor());
await testDb.init();
expect(testDb).toBeInstanceOf(SmartdataDb);
});
tap.test('should create test data', async () => {
// Create test users
const users = [
new TestUser({
name: 'John Doe',
age: 30,
email: 'john@example.com',
roles: ['admin', 'user'],
tags: ['javascript', 'nodejs', 'mongodb'],
status: 'active',
metadata: { loginCount: 5, lastLogin: new Date() },
scores: [85, 90, 78]
}),
new TestUser({
name: 'Jane Smith',
age: 25,
email: 'jane@example.com',
roles: ['user'],
tags: ['python', 'mongodb'],
status: 'active',
metadata: { loginCount: 3 },
scores: [92, 88, 95]
}),
new TestUser({
name: 'Bob Johnson',
age: 35,
email: 'bob@example.com',
roles: ['moderator', 'user'],
tags: ['javascript', 'react', 'nodejs'],
status: 'inactive',
metadata: { loginCount: 0 },
scores: [70, 75, 80]
}),
new TestUser({
name: 'Alice Brown',
age: 28,
email: 'alice@example.com',
roles: ['admin'],
tags: ['typescript', 'angular', 'mongodb'],
status: 'active',
metadata: { loginCount: 10 },
scores: [95, 98, 100]
}),
new TestUser({
name: 'Charlie Wilson',
age: 22,
email: 'charlie@example.com',
roles: ['user'],
tags: ['golang', 'kubernetes'],
status: 'pending',
metadata: { loginCount: 1 },
scores: [60, 65]
})
];
for (const user of users) {
await user.save();
}
// Create test orders
const orders = [
new TestOrder({
userId: users[0].id,
items: [
{ product: 'laptop', quantity: 1, price: 1200 },
{ product: 'mouse', quantity: 2, price: 25 }
],
totalAmount: 1250,
status: 'completed',
tags: ['electronics', 'priority']
}),
new TestOrder({
userId: users[1].id,
items: [
{ product: 'book', quantity: 3, price: 15 },
{ product: 'pen', quantity: 5, price: 2 }
],
totalAmount: 55,
status: 'pending',
tags: ['stationery']
}),
new TestOrder({
userId: users[0].id,
items: [
{ product: 'laptop', quantity: 2, price: 1200 },
{ product: 'keyboard', quantity: 2, price: 80 }
],
totalAmount: 2560,
status: 'processing',
tags: ['electronics', 'bulk']
})
];
for (const order of orders) {
await order.save();
}
const savedUsers = await TestUser.getInstances({});
const savedOrders = await TestOrder.getInstances({});
expect(savedUsers.length).toEqual(5);
expect(savedOrders.length).toEqual(3);
});
// ============= BASIC FILTER TESTS =============
tap.test('should filter by simple equality', async () => {
const users = await TestUser.getInstances({ name: 'John Doe' });
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should filter by multiple fields (implicit AND)', async () => {
const users = await TestUser.getInstances({
status: 'active',
age: 30
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should filter by nested object fields', async () => {
const users = await TestUser.getInstances({
'metadata.loginCount': 5
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
// ============= COMPREHENSIVE NESTED FILTER TESTS =============
tap.test('should filter by nested object with direct object syntax', async () => {
// Direct nested object matching (exact match)
const users = await TestUser.getInstances({
metadata: {
loginCount: 5,
lastLogin: (await TestUser.getInstances({}))[0].metadata.lastLogin // Get the exact date
}
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should filter by partial nested object match', async () => {
// When using object syntax, only specified fields must match
const users = await TestUser.getInstances({
metadata: { loginCount: 5 } // Only checks loginCount, ignores other fields
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should combine nested object and dot notation', async () => {
const users = await TestUser.getInstances({
metadata: { loginCount: { $gte: 3 } }, // Object syntax with operator
'metadata.loginCount': { $lte: 10 } // Dot notation with operator
});
expect(users.length).toEqual(3); // Jane (3), John (5), and Alice (10) have loginCount between 3-10
});
tap.test('should filter nested fields with operators using dot notation', async () => {
const users = await TestUser.getInstances({
'metadata.loginCount': { $gte: 5 }
});
expect(users.length).toEqual(2); // John (5) and Alice (10)
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'John Doe']);
});
tap.test('should filter nested fields with multiple operators', async () => {
const users = await TestUser.getInstances({
'metadata.loginCount': { $gte: 3, $lt: 10 }
});
expect(users.length).toEqual(2); // Jane (3) and John (5)
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Jane Smith', 'John Doe']);
});
tap.test('should handle deeply nested object structures', async () => {
// First, create a user with deep nesting in preferences
const deepUser = new TestUser({
name: 'Deep Nester',
age: 40,
email: 'deep@example.com',
roles: ['admin'],
tags: [],
status: 'active',
metadata: {
loginCount: 1,
preferences: {
theme: {
colors: {
primary: '#000000',
secondary: '#ffffff'
},
fonts: {
heading: 'Arial',
body: 'Helvetica'
}
},
notifications: {
email: true,
push: false
}
}
},
scores: []
});
await deepUser.save();
// Test deep nesting with dot notation
const deepResults = await TestUser.getInstances({
'metadata.preferences.theme.colors.primary': '#000000'
});
expect(deepResults.length).toEqual(1);
expect(deepResults[0].name).toEqual('Deep Nester');
// Test deep nesting with operators
const boolResults = await TestUser.getInstances({
'metadata.preferences.notifications.email': { $eq: true }
});
expect(boolResults.length).toEqual(1);
expect(boolResults[0].name).toEqual('Deep Nester');
// Clean up
await deepUser.delete();
});
tap.test('should filter arrays of nested objects using $elemMatch', async () => {
const orders = await TestOrder.getInstances({
items: {
$elemMatch: {
product: 'laptop',
price: { $gte: 1000 }
}
}
});
expect(orders.length).toEqual(2); // Both laptop orders have price >= 1000
});
tap.test('should filter nested arrays with dot notation', async () => {
// Query for any order that has an item with specific product
const orders = await TestOrder.getInstances({
'items.product': 'laptop'
});
expect(orders.length).toEqual(2); // Two orders contain laptops
});
tap.test('should combine nested object filters with logical operators', async () => {
const users = await TestUser.getInstances({
$or: [
{ 'metadata.loginCount': { $gte: 10 } }, // Alice has 10
{
$and: [
{ 'metadata.loginCount': { $lt: 5 } }, // Jane has 3, Bob has 0, Charlie has 1
{ status: 'active' } // Jane is active, Bob is inactive, Charlie is pending
]
}
]
});
expect(users.length).toEqual(2); // Alice (loginCount >= 10), Jane (loginCount < 5 AND active)
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'Jane Smith']);
});
tap.test('should handle null and undefined in nested fields', async () => {
// Users without lastLogin
const noLastLogin = await TestUser.getInstances({
'metadata.lastLogin': { $exists: false }
});
expect(noLastLogin.length).toEqual(4); // Everyone except John
// Users with preferences (none have it set)
const withPreferences = await TestUser.getInstances({
'metadata.preferences': { $exists: true }
});
expect(withPreferences.length).toEqual(0);
});
tap.test('should filter nested arrays by size', async () => {
// Create an order with specific number of items
const multiItemOrder = new TestOrder({
userId: 'test-user',
items: [
{ product: 'item1', quantity: 1, price: 10 },
{ product: 'item2', quantity: 2, price: 20 },
{ product: 'item3', quantity: 3, price: 30 },
{ product: 'item4', quantity: 4, price: 40 }
],
totalAmount: 100,
status: 'pending',
tags: ['test']
});
await multiItemOrder.save();
const fourItemOrders = await TestOrder.getInstances({
items: { $size: 4 }
});
expect(fourItemOrders.length).toEqual(1);
// Clean up
await multiItemOrder.delete();
});
tap.test('should handle nested field comparison between documents', async () => {
// Find users where loginCount equals their age divided by 6 (John: 30/6=5)
const users = await TestUser.getInstances({
$and: [
{ 'metadata.loginCount': 5 },
{ age: 30 }
]
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should filter using $in on nested fields', async () => {
const users = await TestUser.getInstances({
'metadata.loginCount': { $in: [0, 1, 5] }
});
expect(users.length).toEqual(3); // Bob (0), Charlie (1), John (5)
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Bob Johnson', 'Charlie Wilson', 'John Doe']);
});
tap.test('should filter nested arrays with $all', async () => {
// Create an order with multiple tags
const taggedOrder = new TestOrder({
userId: 'test-user',
items: [{ product: 'test', quantity: 1, price: 10 }],
totalAmount: 10,
status: 'completed',
tags: ['urgent', 'priority', 'electronics']
});
await taggedOrder.save();
const priorityElectronics = await TestOrder.getInstances({
tags: { $all: ['priority', 'electronics'] }
});
expect(priorityElectronics.length).toEqual(2); // Original order and new one
// Clean up
await taggedOrder.delete();
});
// ============= COMPARISON OPERATOR TESTS =============
tap.test('should filter using $gt operator', async () => {
const users = await TestUser.getInstances({
age: { $gt: 30 }
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('Bob Johnson');
});
tap.test('should filter using $gte operator', async () => {
const users = await TestUser.getInstances({
age: { $gte: 30 }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Bob Johnson', 'John Doe']);
});
tap.test('should filter using $lt operator', async () => {
const users = await TestUser.getInstances({
age: { $lt: 25 }
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('Charlie Wilson');
});
tap.test('should filter using $lte operator', async () => {
const users = await TestUser.getInstances({
age: { $lte: 25 }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Charlie Wilson', 'Jane Smith']);
});
tap.test('should filter using $ne operator', async () => {
const users = await TestUser.getInstances({
status: { $ne: 'active' }
});
expect(users.length).toEqual(2);
const statuses = users.map(u => u.status).sort();
expect(statuses).toEqual(['inactive', 'pending']);
});
tap.test('should filter using multiple comparison operators', async () => {
const users = await TestUser.getInstances({
age: { $gte: 25, $lt: 30 }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'Jane Smith']);
});
// ============= ARRAY OPERATOR TESTS =============
tap.test('should filter using $in operator', async () => {
const users = await TestUser.getInstances({
status: { $in: ['active', 'pending'] }
});
expect(users.length).toEqual(4);
expect(users.every(u => ['active', 'pending'].includes(u.status))).toEqual(true);
});
tap.test('should filter arrays using $in operator', async () => {
const users = await TestUser.getInstances({
roles: { $in: ['admin'] }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'John Doe']);
});
tap.test('should filter using $nin operator', async () => {
const users = await TestUser.getInstances({
status: { $nin: ['inactive', 'pending'] }
});
expect(users.length).toEqual(3);
expect(users.every(u => u.status === 'active')).toEqual(true);
});
tap.test('should filter arrays using $all operator', async () => {
const users = await TestUser.getInstances({
tags: { $all: ['javascript', 'nodejs'] }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Bob Johnson', 'John Doe']);
});
tap.test('should filter arrays using $size operator', async () => {
const users = await TestUser.getInstances({
scores: { $size: 2 }
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('Charlie Wilson');
});
tap.test('should filter arrays using $elemMatch operator', async () => {
const orders = await TestOrder.getInstances({
items: {
$elemMatch: {
product: 'laptop',
quantity: { $gte: 2 }
}
}
});
expect(orders.length).toEqual(1);
expect(orders[0].totalAmount).toEqual(2560);
});
tap.test('should filter using $elemMatch with single condition', async () => {
const orders = await TestOrder.getInstances({
items: {
$elemMatch: {
price: { $gt: 100 }
}
}
});
expect(orders.length).toEqual(2);
expect(orders.every(o => o.items.some(i => i.price > 100))).toEqual(true);
});
// ============= LOGICAL OPERATOR TESTS =============
tap.test('should filter using $or operator', async () => {
const users = await TestUser.getInstances({
$or: [
{ age: { $lt: 25 } },
{ status: 'inactive' }
]
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Bob Johnson', 'Charlie Wilson']);
});
tap.test('should filter using $and operator', async () => {
const users = await TestUser.getInstances({
$and: [
{ status: 'active' },
{ age: { $gte: 28 } }
]
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'John Doe']);
});
tap.test('should filter using $nor operator', async () => {
const users = await TestUser.getInstances({
$nor: [
{ status: 'inactive' },
{ age: { $lt: 25 } }
]
});
expect(users.length).toEqual(3);
expect(users.every(u => u.status !== 'inactive' && u.age >= 25)).toEqual(true);
});
tap.test('should filter using nested logical operators', async () => {
const users = await TestUser.getInstances({
$or: [
{
$and: [
{ status: 'active' },
{ roles: { $in: ['admin'] } }
]
},
{ age: { $lt: 23 } }
]
});
expect(users.length).toEqual(3);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'Charlie Wilson', 'John Doe']);
});
// ============= ELEMENT OPERATOR TESTS =============
tap.test('should filter using $exists operator', async () => {
const users = await TestUser.getInstances({
'metadata.lastLogin': { $exists: true }
});
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('John Doe');
});
tap.test('should filter using $exists false', async () => {
const users = await TestUser.getInstances({
'metadata.preferences': { $exists: false }
});
expect(users.length).toEqual(5);
});
// ============= COMPLEX FILTER TESTS =============
tap.test('should handle complex nested filters', async () => {
const users = await TestUser.getInstances({
$and: [
{ status: 'active' },
{
$or: [
{ age: { $gte: 30 } },
{ roles: { $all: ['admin'] } }
]
},
{ tags: { $in: ['mongodb'] } }
]
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Alice Brown', 'John Doe']);
});
tap.test('should combine multiple operator types', async () => {
const orders = await TestOrder.getInstances({
$and: [
{ totalAmount: { $gte: 100 } },
{ status: { $in: ['completed', 'processing'] } },
{ tags: { $in: ['electronics'] } }
]
});
expect(orders.length).toEqual(2);
expect(orders.every(o => o.totalAmount >= 100)).toEqual(true);
});
// ============= ERROR HANDLING TESTS =============
tap.test('should throw error for $where operator', async () => {
let error: Error | null = null;
try {
await TestUser.getInstances({
$where: 'this.age > 25'
});
} catch (e) {
error = e as Error;
}
expect(error).toBeTruthy();
expect(error?.message).toMatch(/\$where.*not allowed/);
});
tap.test('should throw error for invalid $in value', async () => {
let error: Error | null = null;
try {
await TestUser.getInstances({
status: { $in: 'active' as any } // Should be an array
});
} catch (e) {
error = e as Error;
}
expect(error).toBeTruthy();
expect(error?.message).toMatch(/\$in.*requires.*array/);
});
tap.test('should throw error for invalid $size value', async () => {
let error: Error | null = null;
try {
await TestUser.getInstances({
scores: { $size: '3' as any } // Should be a number
});
} catch (e) {
error = e as Error;
}
expect(error).toBeTruthy();
expect(error?.message).toMatch(/\$size.*requires.*numeric/);
});
tap.test('should throw error for dots in field names', async () => {
let error: Error | null = null;
try {
await TestUser.getInstances({
'some.nested.field': { 'invalid.key': 'value' }
});
} catch (e) {
error = e as Error;
}
expect(error).toBeTruthy();
expect(error?.message).toMatch(/keys cannot contain dots/);
});
// ============= EDGE CASE TESTS =============
tap.test('should handle empty filter (return all)', async () => {
const users = await TestUser.getInstances({});
expect(users.length).toEqual(5);
});
tap.test('should handle null values in filter', async () => {
// First, create a user with null email
const nullUser = new TestUser({
name: 'Null User',
age: 40,
email: null as any,
roles: ['user'],
tags: [],
status: 'active',
metadata: {},
scores: []
});
await nullUser.save();
const users = await TestUser.getInstances({ email: null });
expect(users.length).toEqual(1);
expect(users[0].name).toEqual('Null User');
// Clean up
await nullUser.delete();
});
tap.test('should handle arrays as direct equality match', async () => {
// This tests that arrays without operators are treated as equality matches
const users = await TestUser.getInstances({
roles: ['user'] // Exact match for array
});
expect(users.length).toEqual(2); // Both Jane and Charlie have exactly ['user']
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Charlie Wilson', 'Jane Smith']);
});
tap.test('should handle regex operator', async () => {
const users = await TestUser.getInstances({
name: { $regex: '^J', $options: 'i' }
});
expect(users.length).toEqual(2);
const names = users.map(u => u.name).sort();
expect(names).toEqual(['Jane Smith', 'John Doe']);
});
tap.test('should handle unknown operators by letting MongoDB reject them', async () => {
// Unknown operators should be passed through to MongoDB, which will reject them
let error: Error | null = null;
try {
await TestUser.getInstances({
age: { $unknownOp: 30 } as any
});
} catch (e) {
error = e as Error;
}
expect(error).toBeTruthy();
expect(error?.message).toMatch(/unknown operator.*\$unknownOp/);
});
// ============= PERFORMANCE TESTS =============
tap.test('should efficiently filter large result sets', async () => {
// Create many test documents
const manyUsers = [];
for (let i = 0; i < 100; i++) {
manyUsers.push(new TestUser({
name: `User ${i}`,
age: 20 + (i % 40),
email: `user${i}@example.com`,
roles: i % 3 === 0 ? ['admin'] : ['user'],
tags: i % 2 === 0 ? ['even', 'test'] : ['odd', 'test'],
status: i % 4 === 0 ? 'inactive' : 'active',
metadata: { loginCount: i },
scores: [i, i + 10, i + 20]
}));
}
// Save in batches for efficiency
for (const user of manyUsers) {
await user.save();
}
// Complex filter that should still be fast
const startTime = Date.now();
const filtered = await TestUser.getInstances({
$and: [
{ age: { $gte: 30, $lt: 40 } },
{ status: 'active' },
{ tags: { $in: ['even'] } },
{ 'metadata.loginCount': { $gte: 20 } }
]
});
const duration = Date.now() - startTime;
console.log(`Complex filter on 100+ documents took ${duration}ms`);
expect(duration).toBeLessThan(1000); // Should complete in under 1 second
expect(filtered.length).toBeGreaterThan(0);
// Clean up
for (const user of manyUsers) {
await user.delete();
}
});
// ============= CLEANUP =============
tap.test('should clean up test database', async () => {
await testDb.mongoDb.dropDatabase();
await testDb.close();
await smartmongoInstance.stop();
});
export default tap.start();

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartdata',
version: '5.16.1',
version: '5.16.4',
description: 'An advanced library for NoSQL data organization and manipulation using TypeScript with support for MongoDB, data validation, collections, and custom data types.'
}

View File

@@ -151,48 +151,181 @@ export function index(options?: IIndexOptions) {
};
}
// Helper type to extract element type from arrays or return T itself
type ElementOf<T> = T extends ReadonlyArray<infer U> ? U : T;
// Type for $in/$nin values - arrays of the element type
type InValues<T> = ReadonlyArray<ElementOf<T>>;
// Type that allows MongoDB operators on leaf values while maintaining nested type safety
export type MongoFilterCondition<T> = T | {
$eq?: T;
$ne?: T;
$gt?: T;
$gte?: T;
$lt?: T;
$lte?: T;
$in?: InValues<T>;
$nin?: InValues<T>;
$exists?: boolean;
$type?: string | number;
$regex?: string | RegExp;
$options?: string;
$all?: T extends ReadonlyArray<infer U> ? ReadonlyArray<U> : never;
$elemMatch?: T extends ReadonlyArray<infer U> ? MongoFilter<U> : never;
$size?: T extends ReadonlyArray<any> ? number : never;
$not?: MongoFilterCondition<T>;
};
export type MongoFilter<T> = {
[K in keyof T]?: T[K] extends object
? T[K] extends any[]
? MongoFilterCondition<T[K]> // Arrays can have operators
: MongoFilter<T[K]> | MongoFilterCondition<T[K]> // Objects can be nested or have operators
: MongoFilterCondition<T[K]>; // Primitives get operators
} & {
// Logical operators
$and?: MongoFilter<T>[];
$or?: MongoFilter<T>[];
$nor?: MongoFilter<T>[];
$not?: MongoFilter<T>;
// Allow any string key for dot notation (we lose type safety here but maintain flexibility)
[key: string]: any;
};
export const convertFilterForMongoDb = (filterArg: { [key: string]: any }) => {
// Special case: detect MongoDB operators and pass them through directly
// SECURITY: Removed $where to prevent server-side JS execution
const topLevelOperators = ['$and', '$or', '$nor', '$not', '$text', '$regex'];
for (const key of Object.keys(filterArg)) {
if (topLevelOperators.includes(key)) {
return filterArg; // Return the filter as-is for MongoDB operators
// SECURITY: Block $where to prevent server-side JS execution
if (filterArg.$where !== undefined) {
throw new Error('$where operator is not allowed for security reasons');
}
// Handle logical operators recursively
const logicalOperators = ['$and', '$or', '$nor', '$not'];
const processedFilter: { [key: string]: any } = {};
for (const key of Object.keys(filterArg)) {
if (logicalOperators.includes(key)) {
if (key === '$not') {
processedFilter[key] = convertFilterForMongoDb(filterArg[key]);
} else if (Array.isArray(filterArg[key])) {
processedFilter[key] = filterArg[key].map((subFilter: any) => convertFilterForMongoDb(subFilter));
}
}
}
// If only logical operators, return them
const hasOnlyLogicalOperators = Object.keys(filterArg).every(key => logicalOperators.includes(key));
if (hasOnlyLogicalOperators) {
return processedFilter;
}
// Original conversion logic for non-MongoDB query objects
const convertedFilter: { [key: string]: any } = {};
// Helper to merge operator objects
const mergeIntoConverted = (path: string, value: any) => {
const existing = convertedFilter[path];
if (!existing) {
convertedFilter[path] = value;
} else if (
typeof existing === 'object' && !Array.isArray(existing) &&
typeof value === 'object' && !Array.isArray(value) &&
(Object.keys(existing).some(k => k.startsWith('$')) || Object.keys(value).some(k => k.startsWith('$')))
) {
// Both have operators, merge them
convertedFilter[path] = { ...existing, ...value };
} else {
// Otherwise later wins
convertedFilter[path] = value;
}
};
const convertFilterArgument = (keyPathArg2: string, filterArg2: any) => {
if (Array.isArray(filterArg2)) {
// FIX: Properly handle arrays for operators like $in, $all, or plain equality
convertedFilter[keyPathArg2] = filterArg2;
// Arrays are typically used as values for operators like $in or as direct equality matches
mergeIntoConverted(keyPathArg2, filterArg2);
return;
} else if (typeof filterArg2 === 'object' && filterArg2 !== null) {
for (const key of Object.keys(filterArg2)) {
if (key.startsWith('$')) {
// Prevent dangerous operators
if (key === '$where') {
// Check if this is an object with MongoDB operators
const keys = Object.keys(filterArg2);
const hasOperators = keys.some(key => key.startsWith('$'));
if (hasOperators) {
// This object contains MongoDB operators
// Validate and pass through allowed operators
const allowedOperators = [
// Comparison operators
'$eq', '$ne', '$gt', '$gte', '$lt', '$lte',
// Array operators
'$in', '$nin', '$all', '$elemMatch', '$size',
// Element operators
'$exists', '$type',
// Evaluation operators (safe ones only)
'$regex', '$options', '$text', '$mod',
// Logical operators (nested)
'$and', '$or', '$nor', '$not'
];
// Check for dangerous operators
if (keys.includes('$where')) {
throw new Error('$where operator is not allowed for security reasons');
}
convertedFilter[keyPathArg2] = filterArg2;
// Validate all operators are in the allowed list
const invalidOperators = keys.filter(key =>
key.startsWith('$') && !allowedOperators.includes(key)
);
if (invalidOperators.length > 0) {
console.warn(`Warning: Unknown MongoDB operators detected: ${invalidOperators.join(', ')}`);
}
// For array operators, ensure the values are appropriate
if (filterArg2.$in && !Array.isArray(filterArg2.$in)) {
throw new Error('$in operator requires an array value');
}
if (filterArg2.$nin && !Array.isArray(filterArg2.$nin)) {
throw new Error('$nin operator requires an array value');
}
if (filterArg2.$all && !Array.isArray(filterArg2.$all)) {
throw new Error('$all operator requires an array value');
}
if (filterArg2.$size && typeof filterArg2.$size !== 'number') {
throw new Error('$size operator requires a numeric value');
}
// Use merge helper to handle duplicate paths
mergeIntoConverted(keyPathArg2, filterArg2);
return;
} else if (key.includes('.')) {
}
// No operators, check for dots in keys
for (const key of keys) {
if (key.includes('.')) {
throw new Error('keys cannot contain dots');
}
}
for (const key of Object.keys(filterArg2)) {
// Recursively process nested objects
for (const key of keys) {
convertFilterArgument(`${keyPathArg2}.${key}`, filterArg2[key]);
}
} else {
convertedFilter[keyPathArg2] = filterArg2;
// Primitive values
mergeIntoConverted(keyPathArg2, filterArg2);
}
};
for (const key of Object.keys(filterArg)) {
// Skip logical operators, they were already processed
if (!logicalOperators.includes(key)) {
convertFilterArgument(key, filterArg[key]);
}
}
// Add back processed logical operators
Object.assign(convertedFilter, processedFilter);
return convertedFilter;
};
@@ -227,12 +360,12 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
/**
* gets all instances as array
* @param this
* @param filterArg
* @param filterArg - Type-safe MongoDB filter with nested object support and operators
* @returns
*/
public static async getInstances<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T>,
filterArg: MongoFilter<T>,
opts?: { session?: plugins.mongodb.ClientSession }
): Promise<T[]> {
// Pass session through to findAll for transactional queries
@@ -256,7 +389,7 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
*/
public static async getInstance<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T>,
filterArg: MongoFilter<T>,
opts?: { session?: plugins.mongodb.ClientSession }
): Promise<T> {
// Retrieve one document, with optional session for transactions
@@ -289,7 +422,7 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
*/
public static async getCursor<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T>,
filterArg: MongoFilter<T>,
opts?: {
session?: plugins.mongodb.ClientSession;
modifier?: (cursorArg: plugins.mongodb.FindCursor<plugins.mongodb.WithId<plugins.mongodb.BSON.Document>>) => plugins.mongodb.FindCursor<plugins.mongodb.WithId<plugins.mongodb.BSON.Document>>;
@@ -319,7 +452,7 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
*/
public static async watch<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T>,
filterArg: MongoFilter<T>,
opts?: plugins.mongodb.ChangeStreamOptions & { bufferTimeMs?: number },
): Promise<SmartdataDbWatcher<T>> {
const collection: SmartdataCollection<T> = (this as any).collection;
@@ -337,7 +470,7 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
*/
public static async forEach<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T>,
filterArg: MongoFilter<T>,
forEachFunction: (itemArg: T) => Promise<any>,
) {
const cursor: SmartdataDbCursor<T> = await (this as any).getCursor(filterArg);
@@ -349,7 +482,7 @@ export class SmartDataDbDoc<T extends TImplements, TImplements, TManager extends
*/
public static async getCount<T>(
this: plugins.tsclass.typeFest.Class<T>,
filterArg: plugins.tsclass.typeFest.PartialDeep<T> = {} as any,
filterArg: MongoFilter<T> = {} as any,
) {
const collection: SmartdataCollection<T> = (this as any).collection;
return await collection.getCount(filterArg);