-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathroute.ts
More file actions
91 lines (80 loc) · 2.36 KB
/
route.ts
File metadata and controls
91 lines (80 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { cache } from '@/db/Cache';
import db from '@/db';
import { CourseContent } from '@prisma/client';
import Fuse from 'fuse.js';
import { NextRequest, NextResponse } from 'next/server';
export type TSearchedVideos = {
id: number;
parentId: number | null;
title: string;
} & {
parent: { courses: CourseContent[] } | null;
};
const fuzzySearch = (videos: TSearchedVideos[], searchQuery: string) => {
const searchedVideos = new Fuse(videos, {
minMatchCharLength: 3,
keys: ['title'],
}).search(searchQuery);
return searchedVideos.map((video) => video.item);
};
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const searchQuery = searchParams.get('q');
const user = JSON.parse(request.headers.get('g') || '');
if (!user) {
return NextResponse.json({ message: 'User Not Found' }, { status: 400 });
}
if (searchQuery && searchQuery.length > 2) {
const value: TSearchedVideos[] = await cache.get(
'getAllVideosForSearch',
[],
);
if (value) {
return NextResponse.json(fuzzySearch(value, searchQuery));
}
const validityYearsAgo = new Date();
const validityYears = parseInt(process.env.CourseValidityPeriodInYears || "3");
validityYearsAgo.setFullYear(validityYearsAgo.getFullYear() - validityYears);
const allVideos = await db.content.findMany({
where: {
type: 'video',
hidden: false,
parent: {
courses: {
some: {
course: {
purchasedBy: {
some: {
userId: user.id,
assignedAt: {
gte: validityYearsAgo,
},
},
},
},
},
},
},
},
select: {
id: true,
parentId: true,
title: true,
parent: {
select: {
courses: true,
},
},
},
});
cache.set('getAllVideosForSearch', [], allVideos, 24 * 60 * 60);
return NextResponse.json(fuzzySearch(allVideos, searchQuery));
}
} catch (err) {
return NextResponse.json(
{ message: 'Error fetching search results', err },
{ status: 500 },
);
}
}