@andreasnicolaou/query-builder
Version:
A flexible and type-safe query builder for constructing complex conditional expressions with support for nested groups, various operators, and function calls.
87 lines (60 loc) • 3.18 kB
Markdown
# @andreasnicolaou/query-builder
DEMO: https://stackblitz.com/edit/vitejs-vite-grxpgw5w




A flexible, type-safe query builder for constructing complex conditional expressions with support for nested groups, various operators, and function calls.
> **Note:** This is _not_ an ORM and does **not** execute queries or connect to any database. It's a serialization and expression-building utility, ideal for building advanced search/filter UIs, custom DSLs, or backend query engines.
## Features
- Chainable builder API
- Supports multiple operator types (logical, comparison, set, etc.)
- Nested condition grouping
- Type-safe with TypeScript
- Serializable to JSON
- Human-readable string output
## Installation
```bash
npm install @andreasnicolaou/query-builder
```
## Basic Usage
```typescript
import { QueryBuilder } from '@andreasnicolaou/query-builder';
const query = new QueryBuilder()
.where('name', '==', 'Andreas')
.where('age', '>=', 18, 'or')
.group((qb) => {
qb.where('status', 'in', ['active', 'pending']).where('created', '>', new Date('2025-01-01').toISOString());
})
.toString();
console.log(query); // name == 'Andreas' or age >= 18 and (status in ('active', 'pending') and created > '2025-01-01T00:00:00.000Z')
```
## Skipping Empty or Invalid Values
```typescript
import { QueryBuilder } from '@andreasnicolaou/query-builder';
const query = new QueryBuilder()
.skipWhen({ emptyString: true, emptyArray: true })
.where('name', '===', '')
.where('age', '>', 36)
.where('tags', 'in', [])
.toString();
console.log(query); // age > 36
```
## API Highlights
### Core Methods
- `.where(field, operator, value?, logicalOperator?)` - Add a condition
- `.group(callback, logicalOperator?)` - Create nested conditions
- `.skipWhen(options?)` – Configure automatic value skipping (`null`, `undefined`, `''`, `[]`, `NaN` are skipped by default; empty objects are not)
- `.toJSON()` - Get serializable representation
- `.toString()` - Get human-readable string
### Static Helpers
- `QueryBuilder.fn(name, ...args)` - Create function calls for values
## Supported Operators
| Type | Operators |
| ---------- | --------------------------------------------------- |
| Logical | `and`, `or` |
| Comparison | `=`, `==`, `===`, `!=`, `!==`, `>`, `<`, `>=`, `<=` |
| Word | `starts with`, `ends with`, `contains`, `matches` |
| Set | `in`, `not in` |
## Contributing
Contributions are welcome! If you encounter issues or have ideas to enhance the library, feel free to submit an issue or pull request.