1
1
import Minio = require( 'minio' )
2
2
import v4 = require( 'uuid/v4' )
3
+ import axios from 'axios'
3
4
import config = require( '../../config' )
4
5
5
6
const client = new Minio . Client ( {
@@ -17,11 +18,31 @@ export type savedFile = {
17
18
18
19
export const urlForFilename = ( bucket : string , filename : string ) : string => `http${ config . S3 . ssl ? 's' : '' } ://${ config . S3 . endpoint } /${ bucket } /${ filename } `
19
20
21
+ /**
22
+ * Uploads an object to s3 encoded as json
23
+ * @param {object } object
24
+ * @param {string } filename The filename (Default = randomized)
25
+ * @param {string } bucket The bucket name (Default = picked from config.json)
26
+ * @returns {Promise<savedFile> } The etag and url for the file saved
27
+ */
20
28
export const upload = function ( object :object , filename :string = v4 ( ) + '.json' , bucket :string = config . S3 . bucket ) : Promise < savedFile > {
21
29
return new Promise ( ( resolve , reject ) => {
22
30
client . putObject ( bucket , filename , JSON . stringify ( object ) , function ( err , etag ) {
23
31
if ( err ) return reject ( err )
24
32
resolve ( { etag, url : urlForFilename ( bucket , filename ) } )
25
33
} )
26
34
} )
35
+ }
36
+
37
+ /**
38
+ * Downloads a file from url and encodes it
39
+ * @param {string } url
40
+ * @param {string } enc (Default = 'base64')
41
+ * @returns {Promise<string> } the downloaded file encoded as specified
42
+ */
43
+ export const download = async function ( url : string , enc : string = 'base64' ) : Promise < string > {
44
+ if ( ! url ) return ''
45
+
46
+ const { data} = await axios . get ( url )
47
+ return Buffer . from ( data ) . toString ( enc )
27
48
}
0 commit comments