From 9aa198b1667808d5d610b5498ffc4d0e1fb66371 Mon Sep 17 00:00:00 2001 From: Ricardo Berdejo Date: Wed, 27 Jul 2022 17:58:00 +0000 Subject: [PATCH] feat: partial selection (#274) --- README.md | 8 ++++++++ src/paginate.spec.ts | 40 ++++++++++++++++++++++++++++++++++++++++ src/paginate.ts | 13 +++++++++++++ 3 files changed, 61 insertions(+) diff --git a/README.md b/README.md index 03b8979..4053b8b 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,14 @@ const paginateConfig: PaginateConfig { */ 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 diff --git a/src/paginate.spec.ts b/src/paginate.spec.ts index cc612db..4a30671 100644 --- a/src/paginate.spec.ts +++ b/src/paginate.spec.ts @@ -841,4 +841,44 @@ describe('paginate', () => { const result = await paginate(query, catRepo, config) expect(result.meta.totalItems).toBe(cats.length - 1) }) + + it('should return the specified columns only', async () => { + const config: PaginateConfig = { + sortableColumns: ['id'], + select: ['id', 'name'], + } + const query: PaginateQuery = { + path: '', + } + + const result = await paginate(query, catRepo, config) + + result.data.forEach((cat) => { + expect(cat.color).not.toBeDefined() + }) + }) + + it('should return the specified relationship columns only', async () => { + const config: PaginateConfig = { + sortableColumns: ['name'], + select: ['id', 'name', 'toys.name'], + relations: ['toys'], + } + const query: PaginateQuery = { + path: '', + } + + const result = await paginate(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() + }) + }) + }) }) diff --git a/src/paginate.ts b/src/paginate.ts index 6c56949..4bcbf91 100644 --- a/src/paginate.ts +++ b/src/paginate.ts @@ -47,6 +47,7 @@ export interface PaginateConfig { relations?: RelationColumn[] sortableColumns: Column[] searchableColumns?: Column[] + select?: Column[] maxLimit?: number defaultSortBy?: SortBy defaultLimit?: number @@ -224,6 +225,18 @@ export async function paginate( } } + 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))) }