@@ -6,15 +6,35 @@ import * as v from "valibot";
6
6
7
7
export const BLOG_PATH = "parameters/share" ;
8
8
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
+
9
22
const parameters = new Hono ( )
10
23
. get ( "/:id" , async ( c ) => {
11
24
const { id } = c . req . param ( ) ;
12
25
try {
13
- const { url } = await head ( `${ BLOG_PATH } /${ id } .txt ` ) ;
26
+ const { url } = await head ( `${ BLOG_PATH } /${ id } .json ` ) ;
14
27
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
+ ) ;
16
31
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 ) ;
18
38
} catch ( e ) {
19
39
console . error ( `Failed to load playground with id ${ id } : ${ e } ` ) ;
20
40
return c . json ( { code : "" } , 404 ) ;
@@ -29,19 +49,16 @@ const parameters = new Hono()
29
49
} ) ,
30
50
) ,
31
51
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 ) ) ;
34
54
55
+ // Check if the data is larger than 10kb
35
56
if ( bytes . length < 1024 * 10 ) {
36
- // throw new Error
57
+ console . error ( "Data larger than 10kb" ) ;
58
+ return c . json ( { id : "" } , 500 ) ;
37
59
}
38
60
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 ) ;
45
62
return c . json ( { id } ) ;
46
63
} ,
47
64
) ;
0 commit comments