@@ -119,6 +119,56 @@ class WebHelper extends Helper {
119119 tryNextSource ( ) ;
120120 } ) ;
121121 }
122+
123+ /**
124+ * Create or update an asset with provided data. The create function is called if no asset id is provided
125+ * @param {AssetType } assetType - The type of asset to create or update.
126+ * @param {?DataFormat } dataFormat - DataFormat of the data for the stored asset.
127+ * @param {Buffer } data - The data for the cached asset.
128+ * @param {?string } assetId - The ID of the asset to fetch: a project ID, MD5, etc.
129+ * @return {Promise.<object> } A promise for the response from the create or update request
130+ */
131+ store ( assetType , dataFormat , data , assetId ) {
132+ const asset = new Asset ( assetType , assetId , dataFormat ) ;
133+ // If we have an asset id, we should update, otherwise create to get an id
134+ const create = assetId === null || typeof assetId === 'undefined' ;
135+
136+ // Use the first source with the appropriate asset type and url function
137+ const store = this . stores . filter ( s =>
138+ // Only use stores for the incoming asset type
139+ s . types . indexOf ( assetType . name ) !== - 1 && (
140+ // Only use stores that have a create function if this is a create request
141+ // or an update function if this is an update request
142+ ( create && s . create ) || s . update
143+ )
144+ ) [ 0 ] ;
145+
146+ const method = create ? 'post' : 'put' ;
147+
148+ return new Promise ( ( resolve , reject ) => {
149+ if ( ! store ) return reject ( 'No appropriate stores' ) ;
150+
151+ let reqConfig = create ? store . create ( asset ) : store . update ( asset ) ;
152+ if ( typeof reqConfig === 'string' ) {
153+ reqConfig = {
154+ url : reqConfig
155+ } ;
156+ }
157+ return nets ( {
158+ body : data ,
159+ method : method ,
160+ ...reqConfig
161+ } , ( err , resp , body ) => {
162+ if ( err || Math . floor ( resp . statusCode / 100 ) !== 2 ) {
163+ return reject ( err || resp . statusCode ) ;
164+ }
165+ return resolve ( {
166+ id : body [ 'content-name' ] ,
167+ ...body
168+ } ) ;
169+ } ) ;
170+ } ) ;
171+ }
122172}
123173
124174module . exports = WebHelper ;
0 commit comments