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
25 changes: 25 additions & 0 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 @@ -16,6 +18,11 @@ const fuzzySearch = (videos: TSearchedVideos[], searchQuery: string) => {
const searchedVideos = new Fuse(videos, {
minMatchCharLength: 3,
keys: ['title'],
includeScore: true,
threshold: 0.2,
distance: 100,
ignoreLocation: true,
useExtendedSearch: true
}).search(searchQuery);

return searchedVideos.map((video) => video.item);
Expand All @@ -25,6 +32,13 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const searchQuery = searchParams.get('q');

const session = await getServerSession(authOptions);
if (!session || !session.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

const userId = session.user.id;

if (searchQuery && searchQuery.length > 2) {
const value: TSearchedVideos[] = await cache.get(
'getAllVideosForSearch',
Expand All @@ -39,6 +53,17 @@ export async function GET(request: NextRequest) {
where: {
type: 'video',
hidden: false,
courses: {
some: {
course: {
purchasedBy: {
some: {
userId
}
}
}
}
}
},
select: {
id: true,
Expand Down