2023-07-18 21:23:45 +00:00
|
|
|
import { error, json } from '@sveltejs/kit';
|
2024-03-08 19:03:34 +00:00
|
|
|
import { eq } from 'drizzle-orm';
|
|
|
|
|
import db from '$lib/drizzle.js';
|
2024-03-10 19:09:37 +00:00
|
|
|
import { collection_items, users } from '../../../../../schema.js';
|
2023-07-18 21:23:45 +00:00
|
|
|
|
|
|
|
|
// Search a user's collection
|
|
|
|
|
export async function GET({ url, locals, params }) {
|
|
|
|
|
const searchParams = Object.fromEntries(url.searchParams);
|
|
|
|
|
const q = searchParams?.q || '';
|
|
|
|
|
const limit = parseInt(searchParams?.limit) || 10;
|
|
|
|
|
const skip = parseInt(searchParams?.skip) || 0;
|
|
|
|
|
const order = searchParams?.order || 'asc';
|
|
|
|
|
const sort = searchParams?.sort || 'name';
|
|
|
|
|
const collection_id = params.id;
|
|
|
|
|
console.log('url', url);
|
|
|
|
|
console.log('username', locals?.user?.id);
|
|
|
|
|
|
2024-03-10 19:09:37 +00:00
|
|
|
if (!locals.user) {
|
2023-12-27 01:26:39 +00:00
|
|
|
error(401, { message: 'Unauthorized' });
|
2023-07-18 21:23:45 +00:00
|
|
|
}
|
|
|
|
|
|
2024-03-08 19:03:34 +00:00
|
|
|
const collection = await db.query.collections.findFirst({
|
2024-03-10 19:09:37 +00:00
|
|
|
where: eq(users.id, locals?.user?.id)
|
2023-07-18 21:23:45 +00:00
|
|
|
});
|
|
|
|
|
console.log('collection', collection);
|
|
|
|
|
|
|
|
|
|
if (!collection) {
|
|
|
|
|
console.log('Collection was not found');
|
2023-12-27 01:26:39 +00:00
|
|
|
error(404, { message: 'Collection was not found' });
|
2023-07-18 21:23:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2024-03-10 19:09:37 +00:00
|
|
|
const userCollectionItems = await db.query.collection_items.findMany({
|
2024-03-08 19:03:34 +00:00
|
|
|
where: eq(collection_items.collection_id, collection_id),
|
2024-03-10 19:09:37 +00:00
|
|
|
with: {
|
2023-07-18 21:23:45 +00:00
|
|
|
game: {
|
2024-03-10 19:09:37 +00:00
|
|
|
columns: {
|
2023-07-18 21:23:45 +00:00
|
|
|
id: true,
|
|
|
|
|
name: true,
|
|
|
|
|
thumb_url: true
|
2024-03-10 19:09:37 +00:00
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
orderBy: (collection_items, { asc, desc }) => {
|
|
|
|
|
const dbSort = sort === 'dateAdded' ? collection_items.created_at : collection_items.times_played;
|
|
|
|
|
if (order === 'asc') {
|
|
|
|
|
return asc(dbSort);
|
|
|
|
|
} else {
|
|
|
|
|
return desc(dbSort);
|
2023-07-18 21:23:45 +00:00
|
|
|
}
|
|
|
|
|
},
|
2024-03-10 19:09:37 +00:00
|
|
|
offset: skip,
|
|
|
|
|
limit
|
2023-07-18 21:23:45 +00:00
|
|
|
});
|
|
|
|
|
|
2024-03-10 19:09:37 +00:00
|
|
|
return json(userCollectionItems);
|
2023-07-18 21:23:45 +00:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2023-12-27 01:26:39 +00:00
|
|
|
error(500, { message: 'Something went wrong' });
|
2023-07-18 21:23:45 +00:00
|
|
|
}
|
|
|
|
|
}
|