-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathindex.post.ts
More file actions
75 lines (64 loc) · 2.36 KB
/
index.post.ts
File metadata and controls
75 lines (64 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) 2025 The Linux Foundation and each contributor.
// SPDX-License-Identifier: MIT
import type { Pool } from 'pg';
import { CollectionLikeRepository } from '~~/server/repo/collectionLike.repo';
import { InsightsSsoUserRepository } from '~~/server/repo/insightsSsoUser.repo';
import type { DecodedOidcToken } from '~~/types/auth/auth-jwt.types';
import { getAuthUsername } from '~~/server/utils/common';
/**
* API Endpoint: POST /api/collection/like
* Description: Likes a collection for the authenticated user.
*
* Request Body:
* - collectionId (string, required): The ID of the collection to like
*
* Response:
* - 200: Success
* - 400: Validation error
* - 401: Unauthorized
* - 500: Internal Server Error
*/
export default defineEventHandler(async (event): Promise<{ success: boolean } | Error> => {
const user = event.context.user as DecodedOidcToken | undefined;
if (!user?.sub) {
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
}
const body = await readBody<{ collectionId?: string }>(event);
if (!body?.collectionId?.trim()) {
throw createError({ statusCode: 400, statusMessage: 'collectionId is required' });
}
const cmDbPool = event.context.cmDbPool as Pool | undefined;
if (!cmDbPool) {
throw createError({ statusCode: 503, statusMessage: 'Database not available' });
}
try {
const username = getAuthUsername(user.sub);
const ssoUserRepo = new InsightsSsoUserRepository(cmDbPool);
const ssoUser = await ssoUserRepo.upsert({
id: user.sub,
displayName: user.name,
avatarUrl: user.picture,
email: user.email,
username,
});
const collectionId = body.collectionId.trim();
const repo = new CollectionLikeRepository(cmDbPool);
await repo.like(collectionId, ssoUser.id);
return { success: true };
} catch (error: unknown) {
if (error && typeof error === 'object' && 'statusCode' in error) {
throw error;
}
// FK violation means the collection doesn't exist
if (
error &&
typeof error === 'object' &&
'code' in error &&
(error as { code: string }).code === '23503'
) {
throw createError({ statusCode: 404, statusMessage: 'Collection not found' });
}
console.error('Error liking collection:', error);
throw createError({ statusCode: 500, statusMessage: 'Internal Server Error' });
}
});