Skip to content

Commit 60bde7a

Browse files
committed
Handle onError event in request body stream
1 parent 77a19fb commit 60bde7a

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

src/Hyper/Node/Server.purs

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,23 +84,36 @@ instance bufferNodeResponse :: (MonadAff e m)
8484
toResponse buf =
8585
ipure (write buf)
8686

87+
-- Helper function that reads a Stream into a Buffer, and throws error
88+
-- in `Aff` when failed.
8789
readBodyAsBuffer
8890
:: forall e.
8991
HttpRequest
9092
-> Aff (http :: HTTP, avar :: AVAR, buffer :: BUFFER | e) Buffer
9193
readBodyAsBuffer (HttpRequest request _) = do
9294
let stream = HTTP.requestAsStream request
93-
completeBody <- makeVar
95+
bodyResult <- makeVar
9496
chunks <- makeVar' []
95-
res <- liftEff $
96-
catchException (pure <<< Left) (Right <$> fillBody stream chunks completeBody)
97-
either throwError (const (takeVar completeBody)) res
97+
fillResult <- liftEff $
98+
catchException (pure <<< Left) (Right <$> fillBody stream chunks bodyResult)
99+
-- Await the body, or an error.
100+
body <- takeVar bodyResult
101+
-- Return the body, if neither `fillResult` nor `body` is a `Left`.
102+
either throwError pure (fillResult *> body)
98103
where
99-
fillBody stream chunks completeBody = do
104+
fillBody stream chunks bodyResult = do
105+
-- Append all chunks to the body buffer.
100106
Stream.onData stream \chunk ->
101107
void (launchAff (modifyVar (_ <> [chunk]) chunks))
102-
Stream.onEnd stream $
103-
void (launchAff (takeVar chunks >>= concat' >>= putVar completeBody))
108+
-- Complete with `Left` on error.
109+
Stream.onError stream $
110+
void <<< launchAff <<< putVar bodyResult <<< Left
111+
-- Complete with `Right` on successful "end" event.
112+
Stream.onEnd stream $ void $ launchAff $
113+
takeVar chunks
114+
>>= concat'
115+
>>= (pure <<< Right)
116+
>>= putVar bodyResult
104117
concat' = liftEff <<< Buffer.concat
105118

106119
instance readableBodyHttpRequestString :: (Monad m, MonadAff (http :: HTTP, avar :: AVAR, buffer :: BUFFER | e) m)

0 commit comments

Comments
 (0)