|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { getClientIp, type Hook } from "@rehooks/utils"; |
| 3 | +import { ratelimit } from "@/lib/redis/ratelimit"; |
| 4 | +import { join } from "path"; |
| 5 | +import { readFile } from "fs"; |
| 6 | + |
| 7 | +export const dynamic = "force-dynamic"; |
| 8 | + |
| 9 | +const filePath = join(process.cwd(), "lib", "db", "react.json"); |
| 10 | + |
| 11 | +async function loadData(): Promise<Hook[]> { |
| 12 | + return new Promise((resolve, reject) => { |
| 13 | + readFile(filePath, "utf8", (err, data) => { |
| 14 | + if (err) { |
| 15 | + console.error("Error loading data:", err); |
| 16 | + reject(err); |
| 17 | + } else { |
| 18 | + resolve(JSON.parse(data)); |
| 19 | + } |
| 20 | + }); |
| 21 | + }); |
| 22 | +} |
| 23 | + |
| 24 | +export async function GET(req: NextRequest) { |
| 25 | + const clientIp = await getClientIp(); |
| 26 | + const identifier = clientIp; |
| 27 | + const rateLimitResult = await ratelimit.limit(identifier); |
| 28 | + |
| 29 | + NextResponse.next().headers.set( |
| 30 | + "X-RateLimit-Limit", |
| 31 | + rateLimitResult.limit.toString(), |
| 32 | + ); |
| 33 | + NextResponse.next().headers.set( |
| 34 | + "X-RateLimit-Remaining", |
| 35 | + rateLimitResult.remaining.toString(), |
| 36 | + ); |
| 37 | + |
| 38 | + try { |
| 39 | + const url = new URL(req.url); |
| 40 | + const limit = url.searchParams.get("limit"); |
| 41 | + const search = url.searchParams.get("search"); |
| 42 | + const data: Hook[] = await loadData(); |
| 43 | + let result = data; |
| 44 | + if (search) { |
| 45 | + result = data.filter((hook) => |
| 46 | + hook.title.toLowerCase().includes(search.toLowerCase()), |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + if (limit) { |
| 51 | + const parsedLimit = Number(limit); |
| 52 | + if (isNaN(parsedLimit) || parsedLimit <= 0) { |
| 53 | + return NextResponse.json( |
| 54 | + { error: "Invalid limit. It must be a positive number." }, |
| 55 | + { status: 400 }, |
| 56 | + ); |
| 57 | + } |
| 58 | + result = result.slice(0, parsedLimit); |
| 59 | + } |
| 60 | + |
| 61 | + if (!rateLimitResult.success) { |
| 62 | + return NextResponse.json( |
| 63 | + { error: "Ratelimit exceeded. Please try again in a few seconds." }, |
| 64 | + { status: 429 }, |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + return NextResponse.json(result, { |
| 69 | + status: 200, |
| 70 | + headers: { |
| 71 | + "Access-Control-Allow-Origin": "*", |
| 72 | + "Access-Control-Allow-Methods": "GET", |
| 73 | + "Access-Control-Allow-Headers": "Content-Type, Authorization", |
| 74 | + }, |
| 75 | + }); |
| 76 | + } catch (error) { |
| 77 | + console.error("Error:", error); |
| 78 | + return NextResponse.json( |
| 79 | + { error: "Internal Server Error" }, |
| 80 | + { |
| 81 | + status: 500, |
| 82 | + }, |
| 83 | + ); |
| 84 | + } |
| 85 | +} |
0 commit comments