@@ -123,21 +123,6 @@ export default class PaymasterWorker extends Worker {
123123 await super . start ( ) ;
124124 }
125125
126- /**
127- * Fetches tariff plans from database and keeps them cached
128- */
129- private async fetchPlans ( ) : Promise < void > {
130- if ( ! this . plansCollection ) {
131- throw new Error ( 'Plans collection is not initialized' ) ;
132- }
133-
134- this . plans = await this . plansCollection . find ( { } ) . toArray ( ) ;
135-
136- if ( this . plans . length === 0 ) {
137- throw new Error ( 'Please add tariff plans to the database' ) ;
138- }
139- }
140-
141126 /**
142127 * Finds plan by id from cached plans
143128 */
@@ -185,6 +170,48 @@ export default class PaymasterWorker extends Worker {
185170 }
186171 }
187172
173+ /**
174+ * Fetches tariff plans from database and keeps them cached
175+ */
176+ private async fetchPlans ( ) : Promise < void > {
177+ if ( ! this . plansCollection ) {
178+ throw new Error ( 'Plans collection is not initialized' ) ;
179+ }
180+
181+ this . plans = await this . plansCollection . find ( { } ) . toArray ( ) ;
182+
183+ if ( this . plans . length === 0 ) {
184+ throw new Error ( 'Please add tariff plans to the database' ) ;
185+ }
186+ }
187+
188+ /**
189+ * Finds plan by id from cached plans
190+ */
191+ private findPlanById ( planId : WorkspaceDBScheme [ 'tariffPlanId' ] ) : PlanDBScheme | undefined {
192+ return this . plans . find ( ( plan ) => plan . _id . toString ( ) === planId . toString ( ) ) ;
193+ }
194+
195+ /**
196+ * Returns workspace plan, refreshes cache when plan is missing
197+ */
198+ private async getWorkspacePlan ( workspace : WorkspaceDBScheme ) : Promise < PlanDBScheme > {
199+ let currentPlan = this . findPlanById ( workspace . tariffPlanId ) ;
200+
201+ if ( currentPlan ) {
202+ return currentPlan ;
203+ }
204+
205+ await this . fetchPlans ( ) ;
206+ currentPlan = this . findPlanById ( workspace . tariffPlanId ) ;
207+
208+ if ( ! currentPlan ) {
209+ throw new Error ( `[Paymaster] Tariff plan ${ workspace . tariffPlanId . toString ( ) } not found for workspace ${ workspace . _id . toString ( ) } (${ workspace . name } )` ) ;
210+ }
211+
212+ return currentPlan ;
213+ }
214+
188215 /**
189216 * WorkspaceSubscriptionCheckEvent event handler
190217 *
0 commit comments