Skip to content

Commit

Permalink
fix(query): handle array fields in $in operator (#1277)
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed Jun 22, 2022
1 parent 863a36f commit 85ca12a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 12 deletions.
4 changes: 3 additions & 1 deletion src/runtime/query/match/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ function createOperators (match: (...args: any[]) => boolean, operators: Record<
/**
* Match if item is in condition array
**/
$in: (item, condition) => ensureArray(condition).some(cond => match(item, cond)),
$in: (item, condition) => ensureArray(condition).some(
cond => Array.isArray(item) ? match(item, { $contains: cond }) : match(item, cond)
),

/**
* Match if item contains every condition or math every rule in condition array
Expand Down
49 changes: 38 additions & 11 deletions test/features/query/match.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,6 @@ describe('Match', () => {
})
})

test('$in', () => {
const item = { id: 1, name: 'a', to: 'a', category: 'c1', nested: { users: ['Mahatma', 'Steve', 'Woodrow'] } }

expect(match(item, { name: { $in: ['a', 'b'] } })).toBe(true)
expect(match(item, { category: { $in: 'c1' } })).toBe(true)
expect(match(item, { category: { $in: ['c1', 'c2'] } })).toBe(true)
expect(match(item, { category: { $in: ['c2', 'c3'] } })).toBe(false)

expect(match(item, { id: { $in: [1, 2] } })).toBe(true)
})

test('$eq', () => {
// string
expect(match(item, { name: { $eq: 'a' } })).toBe(true)
Expand Down Expand Up @@ -187,4 +176,42 @@ describe('Match', () => {
expect(match(item, { id: { $lte: 0 } })).toBe(false)
})
})

describe('$in ', () => {
test('string filed', () => {
const item = { id: 1, name: 'a', to: 'a', category: 'c1', nested: { users: ['Mahatma', 'Steve', 'Woodrow'] } }

expect(match(item, { name: { $in: ['a', 'b'] } })).toBe(true)
expect(match(item, { category: { $in: 'c1' } })).toBe(true)
expect(match(item, { category: { $in: ['c1', 'c2'] } })).toBe(true)
expect(match(item, { category: { $in: ['c2', 'c3'] } })).toBe(false)

expect(match(item, { id: { $in: [1, 2] } })).toBe(true)
})

test('array field', () => {
const data = [
{
name: 'post1',
tags: ['school', 'office']
},
{
name: 'post2',
tags: ['school', 'home']
},
{
item: 'Maps',
tags: ['office', 'storage']
}
]

const condition = { tags: { $in: ['school', 'home'] } }
data.forEach((item) => {
expect(match(item, condition)).toBe(
item.tags.includes(condition.tags.$in[0]) ||
item.tags.includes(condition.tags.$in[1])
)
})
})
})
})

0 comments on commit 85ca12a

Please sign in to comment.