From deb995015d5b0652c3a480b87611b29e8074483b Mon Sep 17 00:00:00 2001 From: Orion Kindel Date: Tue, 28 Nov 2023 11:15:00 -0600 Subject: [PATCH] feat: rawRequestBodySize --- src/HTTP/Request.js | 14 ++++++++++++++ src/HTTP/Request.purs | 10 ++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/HTTP/Request.js b/src/HTTP/Request.js index 1ce9e68..590de1f 100644 --- a/src/HTTP/Request.js +++ b/src/HTTP/Request.js @@ -1,2 +1,16 @@ /** @type {(_: Blob) => () => Promise} */ export const blobArrayBufferImpl = b => () => b.arrayBuffer() + +/** @type {(_: FormDataEntryValue) => number} */ +const formDataValueSize = v => (typeof v === 'string' ? v.length : v.size) + +/** @type {(_: ArrayBuffer | FormData) => () => number} */ +export const rawRequestBodySize = body => () => + body instanceof ArrayBuffer + ? body.byteLength + : body instanceof FormData + ? Array.from(body.entries()).reduce( + (size, [k, v]) => size + k.length + formDataValueSize(v), + 0, + ) + : 0 diff --git a/src/HTTP/Request.purs b/src/HTTP/Request.purs index 4907fff..8fa90c2 100644 --- a/src/HTTP/Request.purs +++ b/src/HTTP/Request.purs @@ -12,21 +12,21 @@ module HTTP.Request , requestHeaders , requestUrl , requestMethod + , rawRequestBodySize ) where import Prelude import Control.Promise (Promise) import Control.Promise as Promise -import Data.ArrayBuffer.ArrayBuffer as ArrayBuffer import Data.ArrayBuffer.Types (ArrayBuffer) import Data.Map (Map) import Data.Map as Map import Data.Maybe (Maybe(..)) import Data.Newtype (unwrap) import Data.Nullable as Nullable -import Data.Tuple.Containing (class TupleContaining, extract) -import Data.Tuple.Nested (type (/\), (/\)) +import Data.Tuple.Containing (extract) +import Data.Tuple.Nested (type (/\)) import Data.URL (URL) import Effect (Effect) import Effect.Aff.Class (class MonadAff, liftAff) @@ -45,9 +45,11 @@ import Unsafe.Coerce (unsafeCoerce) import Web.File.Blob (Blob) import Web.File.Blob as Blob -foreign import blobArrayBufferImpl :: Blob -> Effect (Promise ArrayBuffer) foreign import data RawRequestBody :: Type +foreign import blobArrayBufferImpl :: Blob -> Effect (Promise ArrayBuffer) +foreign import rawRequestBodySize :: RawRequestBody -> Effect Int + unsafeEmptyRawRequestBody :: RawRequestBody unsafeEmptyRawRequestBody = unsafeCoerce Nullable.null