Optimized bookmarks endpoint to be less verbose

This commit is contained in:
FifthWit 2025-10-25 13:01:43 -05:00
parent b956aa7297
commit 0e45ff1b70
2 changed files with 15 additions and 88 deletions

View file

@ -1,7 +1,6 @@
import { useAuth } from '~/utils/auth';
import { z } from 'zod';
import { scopedLogger } from '~/utils/logger';
import { bookmarks } from '@prisma/client';
const log = scopedLogger('user-bookmarks');
@ -12,7 +11,6 @@ const bookmarkMetaSchema = z.object({
type: z.enum(['movie', 'show']),
});
// Support both formats: direct fields or nested under meta
const bookmarkRequestSchema = z.object({
meta: bookmarkMetaSchema.optional(),
tmdbId: z.string().optional(),
@ -23,14 +21,10 @@ const bookmarkRequestSchema = z.object({
export default defineEventHandler(async event => {
const userId = getRouterParam(event, 'id');
const tmdbId = getRouterParam(event, 'tmdbid');
const session = await useAuth().getCurrentSession();
if (session.user !== userId) {
throw createError({
statusCode: 403,
message: 'Cannot access bookmarks for other users',
});
throw createError({ statusCode: 403, message: 'Cannot access bookmarks for other users' });
}
if (event.method === 'POST') {
@ -38,51 +32,18 @@ export default defineEventHandler(async event => {
const body = await readBody(event);
log.info('Creating bookmark', { userId, tmdbId, body });
// Parse and validate the request body
const validatedRequest = bookmarkRequestSchema.parse(body);
// Extract the meta data - either directly from meta field or from the root
const metaData = validatedRequest.meta || body;
// Validate the meta data separately
const validatedMeta = bookmarkMetaSchema.parse(metaData);
// Extract group from the validated request
const groupFromBody = validatedRequest.group;
// Normalize group to always be an array if present
const normalizedGroup = groupFromBody
? (Array.isArray(groupFromBody) ? groupFromBody : [groupFromBody])
: [];
// Normalize favoriteEpisodes to always be an array
const normalizedFavoriteEpisodes = validatedRequest.favoriteEpisodes || [];
const validated = bookmarkRequestSchema.parse(body);
const meta = bookmarkMetaSchema.parse(validated.meta || body);
const group = validated.group ? (Array.isArray(validated.group) ? validated.group : [validated.group]) : [];
const favoriteEpisodes = validated.favoriteEpisodes || [];
const bookmark = await prisma.bookmarks.upsert({
where: {
tmdb_id_user_id: {
tmdb_id: tmdbId,
user_id: session.user,
},
},
update: {
meta: validatedMeta,
group: normalizedGroup,
favorite_episodes: normalizedFavoriteEpisodes,
updated_at: new Date(),
} as any,
create: {
user_id: session.user,
tmdb_id: tmdbId,
meta: validatedMeta,
group: normalizedGroup,
favorite_episodes: normalizedFavoriteEpisodes,
updated_at: new Date(),
} as any,
}) as bookmarks;
where: { tmdb_id_user_id: { tmdb_id: tmdbId, user_id: session.user } },
update: { meta, group, favorite_episodes: favoriteEpisodes, updated_at: new Date() },
create: { user_id: session.user, tmdb_id: tmdbId, meta, group, favorite_episodes: favoriteEpisodes, updated_at: new Date() },
});
log.info('Bookmark created successfully', { userId, tmdbId });
return {
tmdbId: bookmark.tmdb_id,
meta: bookmark.meta,
@ -91,51 +52,20 @@ export default defineEventHandler(async event => {
updatedAt: bookmark.updated_at,
};
} catch (error) {
log.error('Failed to create bookmark', {
userId,
tmdbId,
error: error instanceof Error ? error.message : String(error),
});
if (error instanceof z.ZodError) {
throw createError({
statusCode: 400,
message: JSON.stringify(error.errors, null, 2),
});
}
log.error('Failed to create bookmark', { userId, tmdbId, error: error instanceof Error ? error.message : String(error) });
if (error instanceof z.ZodError) throw createError({ statusCode: 400, message: JSON.stringify(error.errors, null, 2) });
throw error;
}
} else if (event.method === 'DELETE') {
log.info('Deleting bookmark', { userId, tmdbId });
try {
await prisma.bookmarks.delete({
where: {
tmdb_id_user_id: {
tmdb_id: tmdbId,
user_id: session.user,
},
},
});
await prisma.bookmarks.delete({ where: { tmdb_id_user_id: { tmdb_id: tmdbId, user_id: session.user } } });
log.info('Bookmark deleted successfully', { userId, tmdbId });
return { success: true, tmdbId };
} catch (error) {
log.error('Failed to delete bookmark', {
userId,
tmdbId,
error: error instanceof Error ? error.message : String(error),
});
// If bookmark doesn't exist, still return success
return { success: true, tmdbId };
log.error('Failed to delete bookmark', { userId, tmdbId, error: error instanceof Error ? error.message : String(error) });
}
return { success: true, tmdbId };
}
throw createError({
statusCode: 405,
message: 'Method not allowed',
});
throw createError({ statusCode: 405, message: 'Method not allowed' });
});

View file

@ -1,3 +0,0 @@
export default defineEventHandler(() => {
return;
});