⚙️ Protect /api/svgs & /api/categories.

This commit is contained in:
pheralb 2023-12-17 02:37:50 +00:00
parent 0e7ff01315
commit d4c9b3a316
2 changed files with 34 additions and 2 deletions

View File

@ -1,12 +1,29 @@
import type { RequestEvent } from './$types';
import { json } from '@sveltejs/kit';
import { ratelimit } from '@/server/redis';
// Data:
import { svgs } from '@/data/svgs';
export const GET = () => {
export const GET = async ({ request }: RequestEvent) => {
const categories = svgs
.map((svg) => svg.category)
.filter((category, index, array) => array.indexOf(category) === index);
const ip = request.headers.get('x-forwarded-for') ?? '';
const { success, reset } = await ratelimit.limit(ip);
// Error 429 | If rate limit is exceeded:
if (!success) {
const now = Date.now();
const retryAfter = Math.floor((reset - now) / 1000);
return new Response('Too Many Requests', {
status: 429,
headers: {
'Retry-After': retryAfter.toString()
}
});
}
// Status 200 | If limit is a number:
return json(

View File

@ -2,12 +2,27 @@ import type { RequestEvent } from './$types';
import type { iSVG } from '@/types/svg';
import { error, json } from '@sveltejs/kit';
import { ratelimit } from '@/server/redis';
// Data:
import { svgsData } from '@/data';
export const GET = ({ url }: RequestEvent) => {
export const GET = async ({ url, request }: RequestEvent) => {
const fullUrl = url.origin ?? 'svgl.vercel.app';
const ip = request.headers.get('x-forwarded-for') ?? '';
const { success, reset } = await ratelimit.limit(ip);
// Error 429 | If rate limit is exceeded:
if (!success) {
const now = Date.now();
const retryAfter = Math.floor((reset - now) / 1000);
return new Response('Too Many Requests', {
status: 429,
headers: {
'Retry-After': retryAfter.toString()
}
});
}
// Params:
const getLimitParams = url.searchParams.get('limit');