Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 55 additions & 28 deletions src/app/api/search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import db from '@/db';
import { CourseContent } from '@prisma/client';
import Fuse from 'fuse.js';
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

export type TSearchedVideos = {
id: number;
Expand All @@ -22,40 +24,65 @@ const fuzzySearch = (videos: TSearchedVideos[], searchQuery: string) => {
};

export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const searchQuery = searchParams.get('q');
try {
const { searchParams } = new URL(request.url);
const searchQuery = searchParams.get('q');
const session = await getServerSession(authOptions);

if (searchQuery && searchQuery.length > 2) {
const value: TSearchedVideos[] = await cache.get(
'getAllVideosForSearch',
[],
);

if (value) {
return NextResponse.json(fuzzySearch(value, searchQuery));
if (!session?.user) {
return NextResponse.json({ message: 'User Not Found' }, { status: 401 });
}

const allVideos = await db.content.findMany({
where: {
type: 'video',
hidden: false,
},
select: {
id: true,
parentId: true,
title: true,
parent: {
select: {
courses: true,
if (searchQuery && searchQuery.length > 2) {
const value: TSearchedVideos[] = await cache.get(
'getAllVideosForSearch',
[session.user.id],
);

if (value) {
return NextResponse.json(fuzzySearch(value, searchQuery));
}

const allVideos = await db.content.findMany({
where: {
type: 'video',
hidden: false,
parent: {
courses: {
some: {
course: {
purchasedBy: {
some: {
userId: session.user.id,
},
},
},
},
},
},
},
select: {
id: true,
parentId: true,
title: true,
parent: {
select: {
courses: true,
},
},
},
},
});
});

cache.set('getAllVideosForSearch', [], allVideos, 24 * 60 * 60);
cache.set('getAllVideosForSearch', [session.user.id], allVideos, 24 * 60 * 60);

return NextResponse.json(fuzzySearch(allVideos, searchQuery));
}
return NextResponse.json(fuzzySearch(allVideos, searchQuery));
}

return NextResponse.json({}, { status: 400 });
return NextResponse.json({}, { status: 400 });
} catch (err) {
return NextResponse.json(
{ message: 'Error fetching search results', err },
{ status: 500 },
);
}
}