@@ -403,8 +403,6 @@ export class TrustScoreDatabase {
403
403
}
404
404
}
405
405
406
- // get Or Create Recommender with discord id
407
-
408
406
/**
409
407
* Retrieves an existing recommender or creates a new one if not found.
410
408
* Also initializes metrics for the recommender if they haven't been initialized yet.
@@ -469,6 +467,70 @@ export class TrustScoreDatabase {
469
467
}
470
468
}
471
469
470
+ /**
471
+ * Retrieves an existing recommender or creates a new one if not found.
472
+ * Also initializes metrics for the recommender if they haven't been initialized yet.
473
+ * @param telegramId Telegram ID of the recommender
474
+ * @returns Recommender object with all details, or null if failed
475
+ */
476
+
477
+ async getOrCreateRecommenderWithTelegramId (
478
+ telegramId : string
479
+ ) : Promise < Recommender | null > {
480
+ try {
481
+ // Begin a transaction
482
+ const transaction = this . db . transaction ( ( ) => {
483
+ // Attempt to retrieve the recommender
484
+ const existingRecommender = this . getRecommender ( telegramId ) ;
485
+ if ( existingRecommender ) {
486
+ // Recommender exists, ensure metrics are initialized
487
+ this . initializeRecommenderMetrics ( existingRecommender . id ! ) ;
488
+ return existingRecommender ;
489
+ }
490
+
491
+ // Recommender does not exist, create a new one
492
+ const newRecommender = {
493
+ id : uuidv4 ( ) ,
494
+ address : telegramId ,
495
+ telegramId : telegramId ,
496
+ } ;
497
+ const newRecommenderId = this . addRecommender ( newRecommender ) ;
498
+ if ( ! newRecommenderId ) {
499
+ throw new Error ( "Failed to add new recommender." ) ;
500
+ }
501
+
502
+ // Initialize metrics for the new recommender
503
+ const metricsInitialized =
504
+ this . initializeRecommenderMetrics ( newRecommenderId ) ;
505
+ if ( ! metricsInitialized ) {
506
+ throw new Error (
507
+ "Failed to initialize recommender metrics."
508
+ ) ;
509
+ }
510
+
511
+ // Retrieve and return the newly created recommender
512
+ const recommender = this . getRecommender ( newRecommenderId ) ;
513
+ if ( ! recommender ) {
514
+ throw new Error (
515
+ "Failed to retrieve the newly created recommender."
516
+ ) ;
517
+ }
518
+
519
+ return recommender ;
520
+ } ) ;
521
+
522
+ // Execute the transaction and return the recommender
523
+ const recommenderResult = transaction ( ) ;
524
+ return recommenderResult ;
525
+ } catch ( error ) {
526
+ console . error (
527
+ "Error in getOrCreateRecommenderWithTelegramId:" ,
528
+ error
529
+ ) ;
530
+ return null ;
531
+ }
532
+ }
533
+
472
534
/**
473
535
* Initializes metrics for a recommender if not present.
474
536
* @param recommenderId Recommender's UUID
0 commit comments