@@ -509,23 +509,69 @@ export class PostRepository extends AbstractRepository<PostModel> {
509509 . getOne ( ) ;
510510 }
511511
512+ /**
513+ * Fallback when no embedding-similar posts exist: returns other active posts
514+ * (excluding this post, and excluding same user). Ordered by newest first.
515+ */
516+ public async getSimilarPostsFallback (
517+ excludePostId : string ,
518+ excludeUserId : string ,
519+ limit : number ,
520+ ) : Promise < PostModel [ ] > {
521+ return await this . repository
522+ . createQueryBuilder ( "post" )
523+ . leftJoinAndSelect ( "post.user" , "user" )
524+ . where ( "post.id != :excludePostId" , { excludePostId } )
525+ . andWhere ( "post.archive = false" )
526+ . andWhere ( "post.sold = false" )
527+ . andWhere ( "user.firebaseUid != :excludeUserId" , { excludeUserId } )
528+ . orderBy ( "post.created" , "DESC" )
529+ . limit ( limit )
530+ . getMany ( ) ;
531+ }
532+
533+ /**
534+ * Fallback when even getSimilarPostsFallback is empty (e.g. only one user has posts):
535+ * returns other active posts by any user, excluding only this post.
536+ */
537+ public async getSimilarPostsFallbackIncludeSameUser (
538+ excludePostId : string ,
539+ limit : number ,
540+ ) : Promise < PostModel [ ] > {
541+ return await this . repository
542+ . createQueryBuilder ( "post" )
543+ . leftJoinAndSelect ( "post.user" , "user" )
544+ . where ( "post.id != :excludePostId" , { excludePostId } )
545+ . andWhere ( "post.archive = false" )
546+ . andWhere ( "post.sold = false" )
547+ . orderBy ( "post.created" , "DESC" )
548+ . limit ( limit )
549+ . getMany ( ) ;
550+ }
551+
512552 /*
513553 This method is for getting similar posts for a given post query embedding.
554+ Only returns active, non-archived, unsold posts with embeddings.
555+ Fetches extra candidates so that after filtering (inactive users, blocked users)
556+ we still have at least a few results.
514557 */
515558 public async getSimilarPosts (
516559 queryEmbedding : number [ ] ,
517560 excludePostId : string ,
518561 excludeUserId : string ,
562+ limit = 20 ,
519563 ) : Promise < PostModel [ ] > {
520564 const lit = `[${ queryEmbedding . join ( "," ) } ]` ;
521565 return await this . repository
522566 . createQueryBuilder ( "post" )
523567 . leftJoinAndSelect ( "post.user" , "user" )
524568 . where ( "post.id != :excludePostId" , { excludePostId } )
569+ . andWhere ( "post.embedding IS NOT NULL" )
570+ . andWhere ( "post.archive = false" )
571+ . andWhere ( "post.sold = false" )
525572 . andWhere ( "user.firebaseUid != :excludeUserId" , { excludeUserId } )
526- . orderBy ( `embedding::vector <-> CAST('${ lit } ' AS vector(512))` )
527- . setParameters ( { embedding : queryEmbedding } )
528- . limit ( 10 )
573+ . orderBy ( `post.embedding::vector <-> CAST('${ lit } ' AS vector(512))` )
574+ . limit ( limit )
529575 . getMany ( ) ;
530576 }
531577
0 commit comments