DenisFrezzato / hyper-ts

Type safe middleware architecture for HTTP servers
https://denisfrezzato.github.io/hyper-ts/
MIT License
391 stars 18 forks source link

send file example #34

Open kylegoetz opened 3 years ago

kylegoetz commented 3 years ago

Can we add an example for how to send a file to the user? I would do it, but I am struggling to figure out how. I was thinking about just writing the code as an Express request handler and then wrapping it with fromExpressHandler, but I thought there might be a way to do it purely in hyper-ts.

My first pass is

const sendFileRequestHandler = (fn:string) => (res, req, next) => {
    res.sendFile(fn, next)
}

const sendFile:(fn:string) => H.Middleware<H.StatusOpen, H.ResponseEnded, DomainError, void> = fn => pipe(
    fromRequestHandler(sendFileRequestHandler(fn),constVoid),
    H.ichain(() => pipe(
        H.status(H.Status.OK),
        H.ichain(() => H.closeHeaders()),
        H.ichain(() => H.modifyConnection(c => c.endResponse()))
    )))

declare const controller: H.Middleware<H.StatusOpen, H.StatusOpen, DomainError, Filename> // pre-existing route handler that dynamically creates a file that needs to be sent back to user

pipe(
    controller,
    H.ichain(sendFile))

I wonder if I'm missing something in hyper-ts that I could use to avoid this convoluted way of writing an Express req handler that only sends a file, using fromRequestHandler just to wire it up with my pre-existing controller, and instead just write a single controller.

kylegoetz commented 3 years ago

did a pr adding the functionality #36