Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

parseWhereExpression.md

69 lines1.7 KB

1---
2id: parseWhereExpression
3title: parseWhereExpression
4---
5​
6```ts
7function parseWhereExpression<T>(expr, options): T | null;
8```
9​
10Defined in: [packages/db/src/query/expression-helpers.ts:203](https://github.com/TanStack/db/blob/main/packages/db/src/query/expression-helpers.ts#L203)
11​
12Parses a WHERE expression into a custom format using provided handlers.
13​
14This is the main helper for converting TanStack DB where clauses into your API's filter format.
15You provide handlers for each operator, and this function traverses the expression tree
16and calls the appropriate handlers.
17​
18## Type Parameters
19​
20### T
21​
22`T` = `any`
23​
24## Parameters
25​
26### expr
27​
28The WHERE expression to parse
29​
30`BasicExpression`\<`boolean`\> | `null` | `undefined`
31​
32### options
33​
34[`ParseWhereOptions`](../interfaces/ParseWhereOptions.md)\<`T`\>
35​
36Configuration with handler functions for each operator
37​
38## Returns
39​
40`T` \| `null`
41​
42The parsed result in your custom format
43​
44## Examples
45​
46```typescript
47// REST API with query parameters
48const filters = parseWhereExpression(where, {
49 handlers: {
50 eq: (field, value) => ({ [field.join('.')]: value }),
51 lt: (field, value) => ({ [`${field.join('.')}_lt`]: value }),
52 gt: (field, value) => ({ [`${field.join('.')}_gt`]: value }),
53 and: (...filters) => Object.assign({}, ...filters),
54 or: (...filters) => ({ $or: filters })
55 }
56})
57// Returns: { category: 'electronics', price_lt: 100 }
58```
59​
60```typescript
61// GraphQL where clause
62const where = parseWhereExpression(whereExpr, {
63 handlers: {
64 eq: (field, value) => ({ [field.join('_')]: { _eq: value } }),
65 lt: (field, value) => ({ [field.join('_')]: { _lt: value } }),
66 and: (...filters) => ({ _and: filters })
67 }
68})
69```