@@ -6,15 +6,35 @@ import * as v from "valibot";
66
77export const BLOG_PATH = "parameters/share" ;
88
9+ export const ShareDataSchema = v . object ( { code : v . string ( ) } ) ;
10+ type ShareData = v . InferInput < typeof ShareDataSchema > ;
11+
12+ const putShareData = async ( data : ShareData ) : Promise < string > => {
13+ const id = nanoid ( ) ;
14+ await put ( `${ BLOG_PATH } /${ id } .json` , JSON . stringify ( data ) , {
15+ addRandomSuffix : false ,
16+ access : "public" ,
17+ } ) ;
18+
19+ return id ;
20+ } ;
21+
922const parameters = new Hono ( )
1023 . get ( "/:id" , async ( c ) => {
1124 const { id } = c . req . param ( ) ;
1225 try {
13- const { url } = await head ( `${ BLOG_PATH } /${ id } .txt ` ) ;
26+ const { url } = await head ( `${ BLOG_PATH } /${ id } .json ` ) ;
1427 const res = await fetch ( url ) ;
15- const code = new TextDecoder ( ) . decode ( await res . arrayBuffer ( ) ) ;
28+ const data = JSON . parse (
29+ new TextDecoder ( ) . decode ( await res . arrayBuffer ( ) ) ,
30+ ) ;
1631
17- return c . json ( { code } ) ;
32+ const parsedData = v . safeParse ( ShareDataSchema , data ) ;
33+ if ( ! parsedData . success ) {
34+ return c . json ( { code : "// Something went wrong" } , 500 ) ;
35+ }
36+
37+ return c . json ( parsedData . output ) ;
1838 } catch ( e ) {
1939 console . error ( `Failed to load playground with id ${ id } : ${ e } ` ) ;
2040 return c . json ( { code : "" } , 404 ) ;
@@ -29,19 +49,16 @@ const parameters = new Hono()
2949 } ) ,
3050 ) ,
3151 async ( c ) => {
32- const { code } = c . req . valid ( "json" ) ;
33- const bytes = new TextEncoder ( ) . encode ( code ) ;
52+ const data = c . req . valid ( "json" ) ;
53+ const bytes = new TextEncoder ( ) . encode ( JSON . stringify ( data ) ) ;
3454
55+ // Check if the data is larger than 10kb
3556 if ( bytes . length < 1024 * 10 ) {
36- // throw new Error
57+ console . error ( "Data larger than 10kb" ) ;
58+ return c . json ( { id : "" } , 500 ) ;
3759 }
3860
39- const id = nanoid ( ) ;
40- await put ( `${ BLOG_PATH } /${ id } .txt` , code , {
41- addRandomSuffix : false ,
42- access : "public" ,
43- } ) ;
44-
61+ const id = await putShareData ( data ) ;
4562 return c . json ( { id } ) ;
4663 } ,
4764 ) ;
0 commit comments