Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: basic json column support #1007

Merged
merged 7 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,8 @@ const config: PaginateConfig<CatEntity> = {

`?filter.roles=$contains:moderator,admin` where column `roles` is an array and contains the values `moderator` and `admin`

`?filter.metadata.enabled=$eq:true` where column `metadata` is jsonb and contains an object with the key `enabled`. Json columns is limited to `$eq` operators only.

## Multi Filters

Multi filters are filters that can be applied to a single column with a comparator.
Expand Down
3 changes: 3 additions & 0 deletions src/__tests__/cat-hair.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ export class CatHairEntity {

@CreateDateColumn()
createdAt: string

@Column({ type: 'json', nullable: true })
metadata: Record<string, any>
}
36 changes: 32 additions & 4 deletions src/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
ILike,
In,
IsNull,
JsonContains,
LessThan,
LessThanOrEqual,
MoreThan,
Expand All @@ -20,6 +21,7 @@ import { PaginateQuery } from './decorator'
import {
checkIsArray,
checkIsEmbedded,
checkIsJsonb,
checkIsRelation,
extractVirtualProperty,
fixColumnAlias,
Expand Down Expand Up @@ -165,6 +167,11 @@ export function addWhereCondition<T>(qb: SelectQueryBuilder<T>, column: string,
const isEmbedded = checkIsEmbedded(qb, columnProperties.propertyPath)
const isArray = checkIsArray(qb, columnProperties.propertyName)

/*
const isJsonb = checkIsJsonb(qb, columnProperties.propertyPath)
We might need to add a check with isJsonb here and handle it differently, to solve the missing FROM-clause error. Not sure.
*/

const alias = fixColumnAlias(columnProperties, qb.alias, isRelation, isVirtualProperty, isEmbedded, virtualQuery)
filter[column].forEach((columnFilter: Filter, index: number) => {
const columnNamePerIteration = `${columnProperties.column}${index}`
Expand Down Expand Up @@ -238,7 +245,8 @@ export function parseFilterToken(raw?: string): FilterToken | null {

export function parseFilter(
query: PaginateQuery,
filterableColumns?: { [column: string]: (FilterOperator | FilterSuffix)[] | true }
filterableColumns?: { [column: string]: (FilterOperator | FilterSuffix)[] | true },
qb?: SelectQueryBuilder<unknown>
): ColumnsFilters {
const filter: ColumnsFilters = {}
if (!filterableColumns || !query.filter) {
Expand Down Expand Up @@ -284,6 +292,9 @@ export function parseFilter(
const fixValue = (value: string) =>
isISODate(value) ? new Date(value) : Number.isNaN(Number(value)) ? value : Number(value)

const columnProperties = getPropertiesByColumnName(column)
const isJsonb = checkIsJsonb(qb, columnProperties.propertyPath)

switch (token.operator) {
case FilterOperator.BTW:
params.findOperator = OperatorSymbolToFunction.get(token.operator)(
Expand All @@ -304,7 +315,25 @@ export function parseFilter(
params.findOperator = OperatorSymbolToFunction.get(token.operator)(fixValue(token.value))
}

filter[column] = [...(filter[column] || []), params]
if (isJsonb) {
const parts = column.split('.')
const dbColumnName = parts[parts.length - 2]
const jsonColumnName = parts[parts.length - 1]

const jsonParams = {
comparator: params.comparator,
findOperator: JsonContains({
[jsonColumnName]: fixValue(token.value),
//! Below seems to not be possible from my understanding, https://github.com/typeorm/typeorm/pull/9665
//! This limits the functionaltiy to $eq only for json columns, which is a bit of a shame.
//[jsonColumnName]: params.findOperator,
}),
}

filter[dbColumnName] = [...(filter[column] || []), jsonParams]
} else {
filter[column] = [...(filter[column] || []), params]
}

if (token.suffix) {
const lastFilterElement = filter[column].length - 1
Expand All @@ -314,7 +343,6 @@ export function parseFilter(
}
}
}

return filter
}

Expand All @@ -323,7 +351,7 @@ export function addFilter<T>(
query: PaginateQuery,
filterableColumns?: { [column: string]: (FilterOperator | FilterSuffix)[] | true }
): SelectQueryBuilder<T> {
const filter = parseFilter(query, filterableColumns)
const filter = parseFilter(query, filterableColumns, qb)

const filterEntries = Object.entries(filter)
const orFilters = filterEntries.filter(([_, value]) => value[0].comparator === '$or')
Expand Down
7 changes: 7 additions & 0 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,13 @@ export function checkIsArray(qb: SelectQueryBuilder<unknown>, propertyName: stri
return !!qb?.expressionMap?.mainAlias?.metadata.findColumnWithPropertyName(propertyName)?.isArray
}

export function checkIsJsonb(qb: SelectQueryBuilder<unknown>, propertyName: string): boolean {
if (!qb || !propertyName) {
return false
}
return qb?.expressionMap?.mainAlias?.metadata.findColumnWithPropertyName(propertyName)?.type === 'json'
}

// This function is used to fix the column alias when using relation, embedded or virtual properties
export function fixColumnAlias(
properties: ColumnProperties,
Expand Down
73 changes: 70 additions & 3 deletions src/paginate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,21 @@ describe('paginate', () => {
if (process.env.DB === 'postgres') {
catHairRepo = dataSource.getRepository(CatHairEntity)
catHairs = await catHairRepo.save([
catHairRepo.create({ name: 'short', colors: ['white', 'brown', 'black'] }),
catHairRepo.create({ name: 'long', colors: ['white', 'brown'] }),
catHairRepo.create({ name: 'buzzed', colors: ['white'] }),
catHairRepo.create({
name: 'short',
colors: ['white', 'brown', 'black'],
metadata: { length: 5, thickness: 1 },
}),
catHairRepo.create({
name: 'long',
colors: ['white', 'brown'],
metadata: { length: 20, thickness: 5 },
}),
catHairRepo.create({
name: 'buzzed',
colors: ['white'],
metadata: { length: 0.5, thickness: 10 },
}),
catHairRepo.create({ name: 'none' }),
])
}
Expand Down Expand Up @@ -3051,6 +3063,61 @@ describe('paginate', () => {
})
}

if (process.env.DB === 'postgres') {
describe('should be able to filter on jsonb columns', () => {
it('should filter with single value', async () => {
const config: PaginateConfig<CatHairEntity> = {
sortableColumns: ['id'],
filterableColumns: {
'metadata.length': true,
},
}
const query: PaginateQuery = {
path: '',
filter: {
'metadata.length': '$eq:5',
},
}

const result = await paginate<CatHairEntity>(query, catHairRepo, config)

expect(result.meta.filter).toStrictEqual({
'metadata.length': '$eq:5',
})
expect(result.data).toStrictEqual([catHairs[0]])
expect(result.links.current).toBe('?page=1&limit=20&sortBy=id:ASC&filter.metadata.length=$eq:5')
})

it('should filter with multiple values', async () => {
const config: PaginateConfig<CatHairEntity> = {
sortableColumns: ['id'],
filterableColumns: {
'metadata.length': true,
'metadata.thickness': true,
},
}
const query: PaginateQuery = {
path: '',
filter: {
'metadata.length': '$eq:20',
'metadata.thickness': '$eq:5',
},
}

const result = await paginate<CatHairEntity>(query, catHairRepo, config)

expect(result.meta.filter).toStrictEqual({
'metadata.length': '$eq:20',
'metadata.thickness': '$eq:5',
})
expect(result.data).toStrictEqual([catHairs[1]])
expect(result.links.current).toBe(
'?page=1&limit=20&sortBy=id:ASC&filter.metadata.length=$eq:20&filter.metadata.thickness=$eq:5'
)
})
})
}

if (process.env.DB !== 'postgres') {
describe('should return result based on virtual column', () => {
it('should return result sorted and filter by a virtual column in main entity', async () => {
Expand Down