diff --git a/keyserver/src/services/blob.js b/keyserver/src/services/blob.js index 271a2285d..99bbfb3a3 100644 --- a/keyserver/src/services/blob.js +++ b/keyserver/src/services/blob.js @@ -1,61 +1,61 @@ // @flow import blobService from 'lib/facts/blob-service.js'; import { makeBlobServiceEndpointURL } from 'lib/utils/blob-service.js'; import { getMessageForException } from 'lib/utils/errors.js'; -async function upload(blob: Blob, hash: string, holder: string): Promise { +async function uploadBlob(blob: Blob, hash: string): Promise { const formData = new FormData(); formData.append('blob_hash', hash); formData.append('blob_data', blob); - const assignHolderPromise = fetch( + const uploadBlobResponse = await fetch( + makeBlobServiceEndpointURL(blobService.httpEndpoints.UPLOAD_BLOB), + { + method: blobService.httpEndpoints.UPLOAD_BLOB.method, + body: formData, + }, + ); + + if (!uploadBlobResponse.ok) { + const { status, statusText } = uploadBlobResponse; + throw new Error(`Payload upload failed with HTTP ${status}: ${statusText}`); + } +} + +async function assignHolder(holder: string, hash: string): Promise { + const assignHolderResponse = await fetch( makeBlobServiceEndpointURL(blobService.httpEndpoints.ASSIGN_HOLDER), { method: blobService.httpEndpoints.ASSIGN_HOLDER.method, body: JSON.stringify({ holder, blob_hash: hash, }), headers: { 'content-type': 'application/json', }, }, ); - const uploadHolderPromise = fetch( - makeBlobServiceEndpointURL(blobService.httpEndpoints.UPLOAD_BLOB), - { - method: blobService.httpEndpoints.UPLOAD_BLOB.method, - body: formData, - }, - ); + if (!assignHolderResponse.ok) { + const { status, statusText } = assignHolderResponse; + throw new Error( + `Holder assignment failed with HTTP ${status}: ${statusText}`, + ); + } +} - let assignHolderResponse, uploadBlobResponse; +async function upload(blob: Blob, hash: string, holder: string): Promise { try { - [assignHolderResponse, uploadBlobResponse] = await Promise.all([ - assignHolderPromise, - uploadHolderPromise, - ]); + await Promise.all([assignHolder(holder, hash), uploadBlob(blob, hash)]); } catch (e) { throw new Error( `Payload upload failed with: ${ getMessageForException(e) ?? 'unknown error' }`, ); } - - if (!assignHolderResponse.ok) { - const { status, statusText } = assignHolderResponse; - throw new Error( - `Holder assignment failed with HTTP ${status}: ${statusText}`, - ); - } - - if (!uploadBlobResponse.ok) { - const { status, statusText } = uploadBlobResponse; - throw new Error(`Payload upload failed with HTTP ${status}: ${statusText}`); - } } -export { upload }; +export { upload, uploadBlob, assignHolder };