11import { getCacheAdatper } from '../../cache'
22import { $nsid as likeNsid } from '#shared/types/lexicons/dev/npmx/feed/like.defs'
3+ import type { Backlink } from '~~/shared/utils/constellation'
34
45/**
56 * Likes for a npm package on npmx
@@ -40,6 +41,8 @@ export class PackageLikesUtils {
4041 '.subjectRef' ,
4142 //Limit doesn't matter here since we are just counting the total likes
4243 1 ,
44+ undefined ,
45+ 0 ,
4346 )
4447 return totalLinks . total
4548 }
@@ -60,6 +63,7 @@ export class PackageLikesUtils {
6063 undefined ,
6164 false ,
6265 [ [ usersDid ] ] ,
66+ 0 ,
6367 )
6468 //TODO: need to double check this logic
6569 return userLikes . total > 0
@@ -149,4 +153,55 @@ export class PackageLikesUtils {
149153 userHasLiked : true ,
150154 } as PackageLikes
151155 }
156+
157+ /**
158+ * We need to get the record the user has that they liked the package
159+ * @param packageName
160+ * @param usersDid
161+ * @returns
162+ */
163+ async getTheUsersLikedRecord (
164+ packageName : string ,
165+ usersDid : string ,
166+ ) : Promise < Backlink | undefined > {
167+ const subjectRef = PACKAGE_SUBJECT_REF ( packageName )
168+ const { data : userLikes } = await this . constellation . getBackLinks (
169+ subjectRef ,
170+ likeNsid ,
171+ 'subjectRef' ,
172+ //Limit doesn't matter here since we are just counting the total likes
173+ 1 ,
174+ undefined ,
175+ false ,
176+ [ [ usersDid ] ] ,
177+ 0 ,
178+ )
179+ if ( userLikes . total > 0 && userLikes . records . length > 0 ) {
180+ return userLikes . records [ 0 ]
181+ }
182+ }
183+
184+ /**
185+ * At this point you should have checked if the user had a record for the package on the network and removed it before updating the cache
186+ * @param packageName
187+ * @param usersDid
188+ * @returns
189+ */
190+ async unlikeAPackageAndReturnLikes ( packageName : string , usersDid : string ) : Promise < PackageLikes > {
191+ const totalLikesKey = CACHE_PACKAGE_TOTAL_KEY ( packageName )
192+ const subjectRef = PACKAGE_SUBJECT_REF ( packageName )
193+
194+ let totalLikes = await this . cache . get < number > ( totalLikesKey )
195+ if ( ! totalLikes ) {
196+ totalLikes = await this . constellationLikes ( subjectRef )
197+ }
198+ totalLikes = totalLikes - 1
199+ await this . cache . set ( totalLikesKey , totalLikes , CACHE_MAX_AGE )
200+
201+ await this . cache . delete ( CACHE_USER_LIKES_KEY ( packageName , usersDid ) )
202+ return {
203+ totalLikes : totalLikes ,
204+ userHasLiked : false ,
205+ } as PackageLikes
206+ }
152207}
0 commit comments