From 6a9a5153222565fd9219993bca8db103cf1b9c97 Mon Sep 17 00:00:00 2001 From: Mikhail Yarmaliuk Date: Thu, 16 Mar 2023 18:19:16 +0100 Subject: [PATCH] feat: limit relations --- __tests__/index-test.ts | 15 +++++++++++++++ src/index.ts | 8 +++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/__tests__/index-test.ts b/__tests__/index-test.ts index 572123a..69cc614 100644 --- a/__tests__/index-test.ts +++ b/__tests__/index-test.ts @@ -514,6 +514,21 @@ describe('services/typeorm-json-query', () => { expect(rel[0].alias).to.equal('myRelation'); }); + it('should throw error: reached maximum relation', () => { + const instance = TypeormJsonQuery.init( + { + queryBuilder, + // @ts-ignore + query: { relations: ['testRelation', { name: 'testRelation2' }] }, + }, + { maxRelations: 1 }, + ); + + expect(() => instance.getRelations()).to.throw( + 'Invalid json query: reached maximum relations (1).', + ); + }); + it('should success return relations', () => { const relations = commonInstance.getRelations(); diff --git a/src/index.ts b/src/index.ts index 9e628db..0cb6365 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,6 +32,7 @@ export interface ITypeormJsonQueryOptions { defaultPageSize: number; // 0 - disable (query all items), 200 - default value maxPageSize: number; + maxRelations: number; // level1.level2.level3.etc... maxDeepRelation: number; // { and: [{ and: [{ and: [] }]}] } deep condition level @@ -102,6 +103,7 @@ class TypeormJsonQuery { private readonly options: ITypeormJsonQueryOptions = { defaultPageSize: 25, maxPageSize: 100, + maxRelations: 10, maxDeepRelation: 4, maxDeepWhere: 5, defaultRelationPageSize: 50, @@ -384,7 +386,11 @@ class TypeormJsonQuery { * Get query relations */ public getRelations(relations?: IJsonQuery['relations']): IJsonRelationResult[] { - const { maxDeepRelation, isDisableRelations, relationOptions } = this.options; + const { maxRelations, maxDeepRelation, isDisableRelations, relationOptions } = this.options; + + if ((this.query.relations?.length ?? 0) > maxRelations) { + throw new Error(`Invalid json query: reached maximum relations (${maxRelations}).`); + } const mapRelationOptions = relationOptions!.reduce((res, rel) => { const {