DenisFrezzato / hyper-ts

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

File Upload Example #30

Open n1ru4l opened 4 years ago

n1ru4l commented 4 years ago

File uploads are a common task for a Webserver, right now I have literally no idea how to implement this with hyper-ts. I think many people could benefit from an example that writes a streamed file to the file system.

My current web server that I am planning to migrate to hyper-ts in order learn more about this library uses https://github.com/mscdex/connect-busboy, so I would welcome any example based on it.

mxth commented 4 years ago

You can use fromConnection to get the native request object, and use library like formidable or your own implementation to get the uploaded files.

import { pipe } from 'fp-ts/lib/pipeable'
import * as H from 'hyper-ts'
import * as E from 'fp-ts/lib/Either'
import { IncomingMessage } from 'http'

declare function upload(req: IncomingMessage): Promise<void>

const uploadFile: H.Middleware<H.StatusOpen, H.ResponseEnded, never, void> = pipe(
  H.fromConnection(c =>
    pipe(
      c.getRequest(),
      E.right
    )
  ),
  H.ichain(req =>
    pipe(
      H.status(H.Status.OK),
      H.ichain(_ =>
        H.rightTask(() => upload(req))
      ),
      H.ichain(sendJson)
    )
  ),
  H.orElse(serverError)
)