1+ import File from './file.js'
2+ import Service from './service.js' ;
3+
4+ import { FetchPaginationOptions , FileComputed } from './types.js' ;
5+
6+ export default class Assets {
7+
8+ service : Service ;
9+
10+ constructor ( service : Service ) {
11+ this . service = service
12+ }
13+
14+ async get ( path : string ) {
15+ if ( ! path || path === '/' ) {
16+ throw new TypeError ( 'Path must be provided to get an asset.' ) ;
17+ }
18+
19+ if ( typeof path !== 'string' ) {
20+ throw new TypeError ( 'Path must be a valid string.' ) ;
21+ }
22+
23+ if ( path . endsWith ( '/' ) ) {
24+ throw new TypeError ( 'Path must be a valid asset path.' ) ;
25+ }
26+
27+ const asset = await this . service . fetchAssets ( { path } )
28+
29+ return asset
30+ }
31+
32+ async delete ( path : string ) {
33+ if ( ! path || path === '/' ) {
34+ throw new TypeError ( 'Path must be provided to get an asset.' ) ;
35+ }
36+
37+ if ( typeof path !== 'string' ) {
38+ throw new TypeError ( 'Path must be a valid string.' ) ;
39+ }
40+
41+ await this . service . deleteAsset ( { path } )
42+
43+ return true
44+ }
45+
46+ async list ( path : string , options : FetchPaginationOptions = { } ) {
47+ if ( ! path ) {
48+ path = ''
49+ }
50+
51+ if ( path === '/' ) {
52+ throw new TypeError ( 'Path must be provided to get an asset.' ) ;
53+ }
54+
55+ if ( typeof path !== 'string' ) {
56+ throw new TypeError ( 'Path must be a valid string.' ) ;
57+ }
58+
59+ if ( path !== '' && ! path . endsWith ( '/' ) ) {
60+ throw new TypeError ( 'Path must be a valid path (Ends with "/").' ) ;
61+ }
62+
63+ if ( options ) {
64+ options . limit = options ?. limit ?? 10
65+ }
66+
67+ const asset = await this . service . fetchAssets ( { path, options } )
68+
69+ return asset
70+ }
71+
72+ async put ( path : string , source : string | Buffer ) {
73+ if ( ! path || path === '/' ) {
74+ throw new TypeError ( 'Path must be provided to put an asset.' ) ;
75+ }
76+
77+ if ( typeof path !== 'string' ) {
78+ throw new TypeError ( 'Path must be a valid string.' ) ;
79+ }
80+
81+ if ( path . endsWith ( '/' ) ) {
82+ throw new TypeError ( 'Path must be a valid asset path.' ) ;
83+ }
84+
85+ if ( ! source ) {
86+ throw new TypeError ( 'Source must be provided to put an asset.' ) ;
87+ }
88+
89+ if ( typeof source !== 'string' && ! ( source instanceof Uint8Array ) ) {
90+ throw new TypeError ( 'Source must be a valid string or a buffer array.' ) ;
91+ }
92+
93+ const isBufferSource = source instanceof Uint8Array
94+
95+ let file : FileComputed
96+
97+ if ( isBufferSource ) {
98+ file = { type : 'buffer' , content : source }
99+ } else {
100+ file = await ( new File ( ) . fromFile ( source ) ) . getFile ( )
101+ }
102+
103+ const asset = await this . service . putAsset ( { path, file } )
104+
105+ return asset
106+ }
107+
108+ }
0 commit comments