forked from
npmx.dev/npmx.dev
[READ-ONLY]
a fast, modern browser for the npm registry
1import * as v from 'valibot'
2import { Client } from '@atproto/lex'
3import * as dev from '#shared/types/lexicons/dev'
4import { PackageLikeBodySchema } from '#shared/schemas/social'
5import { throwOnMissingOAuthScope } from '#server/utils/atproto/oauth'
6
7export default eventHandlerWithOAuthSession(async (event, oAuthSession) => {
8 const loggedInUsersDid = oAuthSession?.did.toString()
9
10 if (!oAuthSession || !loggedInUsersDid) {
11 throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
12 }
13
14 //Checks if the user has a scope to like packages
15 await throwOnMissingOAuthScope(oAuthSession, LIKES_SCOPE)
16
17 const body = v.parse(PackageLikeBodySchema, await readBody(event))
18
19 const likesUtil = new PackageLikesUtils()
20
21 const getTheUsersLikedRecord = await likesUtil.getTheUsersLikedRecord(
22 body.packageName,
23 loggedInUsersDid,
24 )
25
26 if (getTheUsersLikedRecord) {
27 const client = new Client(oAuthSession)
28
29 await client.delete(dev.npmx.feed.like, {
30 rkey: getTheUsersLikedRecord.rkey,
31 })
32 const result = await likesUtil.unlikeAPackageAndReturnLikes(body.packageName, loggedInUsersDid)
33 return result
34 } else {
35 // Always unlike in the cache if this endpoint is called. May be a mismatch
36 await likesUtil.setUnlikeInCache(body.packageName, loggedInUsersDid)
37 }
38
39 console.warn(
40 `User ${loggedInUsersDid} tried to unlike a package ${body.packageName} but it was not liked by them.`,
41 )
42
43 return await likesUtil.getLikes(body.packageName, loggedInUsersDid)
44})