Merge pull request #1700 from in-operator-where

feat: add in operator for where filters
This commit is contained in:
typicode
2026-02-18 01:02:13 +01:00
committed by GitHub
5 changed files with 32 additions and 1 deletions

View File

@@ -26,6 +26,12 @@ await test('matchesWhere', async (t) => {
[{ or: [{ a: { lt: 0 } }, { b: { gt: 20 } }] }, false],
[{ nested: { a: { eq: 10 } } }, true],
[{ nested: { b: { lt: 20 } } }, false],
[{ a: { in: [10, 11] } }, true],
[{ a: { in: [1, 2] } }, false],
[{ c: { in: ['x', 'y'] } }, true],
[{ c: { in: ['y', 'z'] } }, false],
[{ a: { in: [10, 11], gt: 9 } }, true],
[{ a: { in: [10, 11], gt: 10 } }, false],
[{ a: { foo: 10 } }, true],
[{ a: { foo: 10, eq: 10 } }, true],
[{ missing: { foo: 1 } }, true],

View File

@@ -53,6 +53,10 @@ export function matchesWhere(obj: JsonObject, where: JsonObject): boolean {
if (knownOps.includes('gte') && !((field as any) >= (op.gte as any))) return false
if (knownOps.includes('eq') && !((field as any) === (op.eq as any))) return false
if (knownOps.includes('ne') && !((field as any) !== (op.ne as any))) return false
if (knownOps.includes('in')) {
const inValues = Array.isArray(op.in) ? op.in : [op.in]
if (!inValues.some((v) => (field as any) === (v as any))) return false
}
continue
}

View File

@@ -83,6 +83,18 @@ await test('parseWhere', async (t) => {
views: { gt: 100, lt: 300 },
},
],
[
'id:in=1,3',
{
id: { in: [1, 3] },
},
],
[
'title_in=hello,world',
{
title: { in: ['hello', 'world'] },
},
],
]
for (const [query, expected] of cases) {

View File

@@ -30,6 +30,15 @@ function splitKey(key: string): { path: string; op: WhereOperator | null } {
function setPathOp(root: JsonObject, path: string, op: WhereOperator, value: string): void {
const fullPath = `${path}.${op}`
if (op === 'in') {
setProperty(
root,
fullPath,
value.split(',').map((part) => coerceValue(part.trim())),
)
return
}
setProperty(root, fullPath, coerceValue(value))
}

View File

@@ -1,4 +1,4 @@
export const WHERE_OPERATORS = ['lt', 'lte', 'gt', 'gte', 'eq', 'ne'] as const
export const WHERE_OPERATORS = ['lt', 'lte', 'gt', 'gte', 'eq', 'ne', 'in'] as const
export type WhereOperator = (typeof WHERE_OPERATORS)[number]