🚀 Update api routes + add categories endpoint.

This commit is contained in:
pheralb 2023-12-17 00:19:56 +00:00
parent 76886347d8
commit 85ddb3fdb8
2 changed files with 67 additions and 3 deletions

View File

@ -0,0 +1,21 @@
import { json } from '@sveltejs/kit';
// Data:
import { svgs } from '@/data/svgs';
export const GET = () => {
const categories = svgs
.map((svg) => svg.category)
.filter((category, index, array) => array.indexOf(category) === index);
// Status 200 | If limit is a number:
return json(
categories.map((category) => {
return {
category,
total: svgs.filter((svg) => svg.category === category).length
};
}),
{ status: 200 }
);
};

View File

@ -7,9 +7,13 @@ import { error, json } from '@sveltejs/kit';
import { svgsData } from '@/data'; import { svgsData } from '@/data';
export const GET = ({ url }: RequestEvent) => { export const GET = ({ url }: RequestEvent) => {
const getParams = url.searchParams.get('limit');
const fullUrl = url.origin ?? 'svgl.vercel.app'; const fullUrl = url.origin ?? 'svgl.vercel.app';
// Params:
const getLimitParams = url.searchParams.get('limit');
const getCategoryParams = url.searchParams.get('category');
const getSearchParams = url.searchParams.get('search');
// Add full route to svgs: // Add full route to svgs:
const fullRouteSvgsData: iSVG[] = svgsData.map((svg) => { const fullRouteSvgsData: iSVG[] = svgsData.map((svg) => {
if (typeof svg.route === 'object' && svg.route !== null) { if (typeof svg.route === 'object' && svg.route !== null) {
@ -30,11 +34,50 @@ export const GET = ({ url }: RequestEvent) => {
}); });
// Status 200 | If no limit is provided, return all svgs: // Status 200 | If no limit is provided, return all svgs:
if (!getParams) { if (!getLimitParams && !getCategoryParams && !getSearchParams) {
return json(fullRouteSvgsData, { status: 200 }); return json(fullRouteSvgsData, { status: 200 });
} }
const limit = Number(getParams); const limit = Number(getLimitParams);
const category = getCategoryParams;
if (category) {
const categorySvgs = fullRouteSvgsData.filter((svg) => {
return svg.category === category.charAt(0).toUpperCase() + category.slice(1);
});
// Error 400 | If category does not exist:
if (categorySvgs.length === 0) {
error(400, {
message: 'Category does not exist.'
});
}
if (!getLimitParams) {
return json(categorySvgs, { status: 200 });
}
return json(categorySvgs.slice(0, limit), { status: 200 });
}
if (getSearchParams) {
const searchSvgs = fullRouteSvgsData.filter((svg) => {
return svg.title.toLowerCase().includes(getSearchParams.toLowerCase());
});
// Error 400 | If search does not exist:
if (searchSvgs.length === 0) {
error(400, {
message: 'Search does not exist.'
});
}
if (!getLimitParams) {
return json(searchSvgs, { status: 200 });
}
return json(searchSvgs.slice(0, limit), { status: 200 });
}
// Error 400 | if limit is not a number: // Error 400 | if limit is not a number:
if (isNaN(limit)) { if (isNaN(limit)) {