feat: partial selection (#274)

This commit is contained in:
Ricardo Berdejo 2022-07-27 17:58:00 +00:00 committed by GitHub
parent bc2723ca7e
commit 9aa198b166
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 61 additions and 0 deletions

View File

@ -171,6 +171,14 @@ const paginateConfig: PaginateConfig<CatEntity> {
*/
searchableColumns: ['name', 'color'],
/**
* Required: false
* Type: TypeORM partial selection
* Default: None
* https://typeorm.io/select-query-builder#partial-selection
*/
select: ['name', 'color'],
/**
* Required: false
* Type: number

View File

@ -841,4 +841,44 @@ describe('paginate', () => {
const result = await paginate<CatEntity>(query, catRepo, config)
expect(result.meta.totalItems).toBe(cats.length - 1)
})
it('should return the specified columns only', async () => {
const config: PaginateConfig<CatEntity> = {
sortableColumns: ['id'],
select: ['id', 'name'],
}
const query: PaginateQuery = {
path: '',
}
const result = await paginate<CatEntity>(query, catRepo, config)
result.data.forEach((cat) => {
expect(cat.color).not.toBeDefined()
})
})
it('should return the specified relationship columns only', async () => {
const config: PaginateConfig<CatEntity> = {
sortableColumns: ['name'],
select: ['id', 'name', 'toys.name'],
relations: ['toys'],
}
const query: PaginateQuery = {
path: '',
}
const result = await paginate<CatEntity>(query, catRepo, config)
result.data.forEach((cat) => {
expect(cat.id).toBeDefined()
expect(cat.name).toBeDefined()
expect(cat.color).not.toBeDefined()
cat.toys.map((toy) => {
expect(toy.name).toBeDefined()
expect(toy.id).not.toBeDefined()
})
})
})
})

View File

@ -47,6 +47,7 @@ export interface PaginateConfig<T> {
relations?: RelationColumn<T>[]
sortableColumns: Column<T>[]
searchableColumns?: Column<T>[]
select?: Column<T>[]
maxLimit?: number
defaultSortBy?: SortBy<T>
defaultLimit?: number
@ -224,6 +225,18 @@ export async function paginate<T>(
}
}
if (config.select?.length > 0) {
const mappedSelect = config.select.map((col) => {
if (col.includes('.')) {
const [rel, relCol] = col.split('.')
return `${queryBuilder.alias}_${rel}.${relCol}`
}
return `${queryBuilder.alias}.${col}`
})
queryBuilder.select(mappedSelect)
}
if (config.where) {
queryBuilder.andWhere(new Brackets((qb) => qb.andWhere(config.where)))
}