1- import { basePath } from "@/config/siteConfig " ;
2- import { Category , Script } from "@/lib/types " ;
1+ import { Metadata , Script } from "@/lib/types " ;
2+ import { promises as fs } from "fs " ;
33import { NextResponse } from "next/server" ;
4+ import path from "path" ;
45
56export const dynamic = "force-static" ;
67
7- const fetchCategories = async ( ) : Promise < Category [ ] > => {
8- const response = await fetch (
9- `https://raw.githubusercontent.com/community-scripts/${ basePath } /refs/heads/main/json/metadata.json` ,
10- ) ;
11- const data = await response . json ( ) ;
12- return data . categories ;
8+ const jsonDir = "public/json" ;
9+ const metadataFileName = "metadata.json" ;
10+ const encoding = "utf-8" ;
11+
12+ const getMetadata = async ( ) => {
13+ const filePath = path . resolve ( jsonDir , metadataFileName ) ;
14+ const fileContent = await fs . readFile ( filePath , encoding ) ;
15+ const metadata : Metadata = JSON . parse ( fileContent ) ;
16+ return metadata ;
1317} ;
1418
15- const fetchScripts = async ( ) : Promise < Script [ ] > => {
16- const response = await fetch (
17- `https://api.github.com/repos/community-scripts/ ${ basePath } /contents/json` ,
18- ) ;
19- const files : { download_url : string } [ ] = await response . json ( ) ;
19+ const getScripts = async ( ) => {
20+ const filePaths = ( await fs . readdir ( jsonDir ) )
21+ . filter ( ( fileName ) => fileName !== metadataFileName )
22+ . map ( ( fileName ) => path . resolve ( jsonDir , fileName ) ) ;
23+
2024 const scripts = await Promise . all (
21- files . map ( async ( file ) : Promise < Script > => {
22- const response = await fetch ( file . download_url ) ;
23- const script = await response . json ( ) ;
25+ filePaths . map ( async ( filePath ) => {
26+ const fileContent = await fs . readFile ( filePath , encoding ) ;
27+ const script : Script = JSON . parse ( fileContent ) ;
2428 return script ;
2529 } ) ,
2630 ) ;
@@ -29,11 +33,18 @@ const fetchScripts = async (): Promise<Script[]> => {
2933
3034export async function GET ( ) {
3135 try {
32- const categories = await fetchCategories ( ) ;
33- const scripts = await fetchScripts ( ) ;
34- for ( const category of categories ) {
35- category . scripts = scripts . filter ( ( script ) => script . categories . includes ( category . id ) ) ;
36- }
36+ const metadata = await getMetadata ( ) ;
37+ const scripts = await getScripts ( ) ;
38+
39+ const categories = metadata . categories
40+ . map ( ( category ) => {
41+ category . scripts = scripts . filter ( ( script ) =>
42+ script . categories . includes ( category . id ) ,
43+ ) ;
44+ return category ;
45+ } )
46+ . sort ( ( a , b ) => a . sort_order - b . sort_order ) ;
47+
3748 return NextResponse . json ( categories ) ;
3849 } catch ( error ) {
3950 console . error ( error as Error ) ;
0 commit comments