@@ -2,38 +2,47 @@ const fs = require('fs').promises;
2
2
const path = require ( 'path' ) ;
3
3
const { commandHash } = require ( './commands' ) ;
4
4
5
+ const exists = async ( dir ) => ! ! await fs . stat ( dir ) . catch ( _err => false ) ;
6
+
5
7
function getFilename ( commandName , name ) {
6
8
const namespace = commandHash ( commandName ) ;
7
9
const cleanName = commandHash ( name ) ;
8
10
return path . join ( __dirname , `../storage/pasta/${ namespace } /${ cleanName } ` ) ;
9
11
}
10
12
11
- async function dirSize ( commandName ) {
12
- const dir = path . join (
13
+ function getDir ( commandName ) {
14
+ return path . join (
13
15
__dirname ,
14
16
`../storage/pasta/${ commandHash ( commandName ) } ` ,
15
17
) ;
16
- const stats = ( await readdir ( dir ) ) . map ( ( file ) =>
18
+ }
19
+
20
+ async function dirSize ( dir ) {
21
+ const stats = ( await fs . readdir ( dir ) ) . map ( ( file ) =>
17
22
fs . stat ( path . join ( dir , file ) ) ,
18
23
) ;
19
24
return ( await Promise . all ( stats ) ) . reduce ( ( acc , { size } ) => acc + size , 0 ) ;
20
25
}
21
26
22
27
async function loadPasta ( commandName , pastaName ) {
23
28
const filename = getFilename ( commandName , pastaName ) ;
24
- if ( ! ( await fs . access ( filename ) ) ) return ;
29
+ if ( ! ( await exists ( filename ) ) ) return ;
25
30
return await fs . readFile ( filename , 'utf8' ) ;
26
31
}
27
32
async function savePasta ( commandName , pastaName , content ) {
28
- if ( ( await dirSize ( commandName ) ) > 20971520 )
33
+ const dir = getDir ( commandName ) ;
34
+ if ( ! await exists ( dir ) ) {
35
+ await fs . mkdir ( dir ) ;
36
+ }
37
+ if ( ( await dirSize ( dir ) ) > 20971520 )
29
38
throw new Error ( 'paste namespace limit is 20MB' ) ;
30
39
const filename = getFilename ( commandName , pastaName ) ;
31
40
if ( typeof content !== 'string' )
32
41
throw new Error ( 'content must be a string' ) ;
33
42
if ( ! content . length ) throw new Error ( 'string cannot be length zero' ) ;
34
43
if ( content . length > 1048576 ) throw new Error ( 'paste size limit is 1MB' ) ;
35
44
await fs . writeFile ( filename , content , 'utf8' ) ;
36
- const url = `/${ commandName } /${ pastaName } ` ;
45
+ const url = `/${ encodeURIComponent ( commandName ) } /${ encodeURIComponent ( pastaName ) } ` ;
37
46
return {
38
47
html : `/html${ url } ` ,
39
48
text : `/text${ url } ` ,
0 commit comments