@@ -43,15 +43,48 @@ export class DbHelper {
4343 *
4444 * @param id - id of the workspace to fetch
4545 */
46- public async getWorkspacesWithTariffPlans ( id : string ) : Promise < WorkspaceWithTariffPlan > ;
46+ public getWorkspacesWithTariffPlans ( id : string ) : Promise < WorkspaceWithTariffPlan > ;
47+ public getWorkspacesWithTariffPlans ( id ?: string ) : AsyncGenerator < WorkspaceWithTariffPlan > | Promise < WorkspaceWithTariffPlan > {
48+ if ( id !== undefined ) {
49+ return this . getOneWorkspaceWithTariffPlan ( id ) ;
50+ }
51+
52+ return this . yieldWorkspacesWithTariffPlans ( ) ;
53+ }
54+
4755 /**
48- * Returns workspace with its tariff plan by its id
56+ * Returns a single workspace with its tariff plan by id
4957 *
5058 * @param id - workspace id
5159 */
52- public async * getWorkspacesWithTariffPlans ( id ?: string ) : AsyncGenerator < WorkspaceWithTariffPlan > | Promise < WorkspaceWithTariffPlan > {
60+ private async getOneWorkspaceWithTariffPlan ( id : string ) : Promise < WorkspaceWithTariffPlan > {
61+ const pipeline = [
62+ {
63+ $match : {
64+ _id : new ObjectId ( id ) ,
65+ } ,
66+ } ,
67+ ...this . tariffPlanLookupPipeline ( ) ,
68+ ] ;
69+
70+ return this . workspacesCollection . aggregate < WorkspaceWithTariffPlan > ( pipeline ) . next ( ) ;
71+ }
72+
73+ /**
74+ * Yields all workspaces with their tariff plans one by one
75+ */
76+ private async * yieldWorkspacesWithTariffPlans ( ) : AsyncGenerator < WorkspaceWithTariffPlan > {
77+ const pipeline = this . tariffPlanLookupPipeline ( ) ;
78+ const cursor = this . workspacesCollection . aggregate < WorkspaceWithTariffPlan > ( pipeline ) ;
79+
80+ for await ( const workspace of cursor ) {
81+ yield workspace ;
82+ }
83+ }
84+
5385 /* eslint-disable-next-line */
54- const queue : any [ ] = [
86+ private tariffPlanLookupPipeline ( ) : any [ ] {
87+ return [
5588 {
5689 $lookup : {
5790 from : 'plans' ,
@@ -66,32 +99,17 @@ export class DbHelper {
6699 } ,
67100 } ,
68101 {
69- projection : {
102+ $project : {
70103 _id : 1 ,
104+ name : 1 ,
71105 isBlocked : 1 ,
106+ blockedDate : 1 ,
72107 lastChargeDate : 1 ,
108+ billingPeriodEventsCount : 1 ,
73109 tariffPlan : 1 ,
74- }
75- }
76- ] ;
77-
78- if ( id !== undefined ) {
79- queue . unshift ( {
80- $match : {
81- _id : new ObjectId ( id ) ,
82110 } ,
83- } ) ;
84- }
85-
86- const workspaces = this . workspacesCollection . aggregate < WorkspaceWithTariffPlan > ( queue ) ;
87-
88- if ( id !== undefined ) {
89- return await workspaces . next ( ) ;
90- }
91-
92- for await ( const workspace of workspaces ) {
93- yield workspace ;
94- }
111+ } ,
112+ ] ;
95113 }
96114
97115 /**
0 commit comments