reason-native-web / morph

A webframework for Reason and OCaml
https://reason-native-web.github.io/morph/
MIT License
139 stars 7 forks source link

Writing middleware documentation is out of date #47

Open Kingdutch opened 4 years ago

Kingdutch commented 4 years ago

https://reason-native-web.github.io/docs/morph/writing-middlewares makes a reference to Morph.Method.to_string but this doesn't actually seem to be in the library.

With some digging I found that the method information from Piaf is actually hidden under request.request.meth so maybe we want to somehow map this to request.method directly (changing Morph.Request.t).

I came up with the following which appears to work.

let method_to_string : Piaf.Method.t => string = fun
  | `GET => "GET"
  | `POST => "POST"
  | `PUT => "PUT"
  | `DELETE => "DELETE"
  | `HEAD => "HEAD"
  | `OPTIONS => "OPTIONS"
  | `TRACE => "TRACE"
  | `CONNECT => "CONNECT"
  | `Other(s) => {j|UNKNOWN($s)|j}
  ;

/**
 * Creates a new logger middleware.
 *
 * The output of this function can be passed to the middlewares
 * argument of `Morph.start`.
 */
let make = () => {
  (service) => (request: Morph.Request.t) => {
    open Lwt.Infix;
    let start_request = Mtime_clock.elapsed();
    service(request)
    >|= (
      response => {
        let end_request = Mtime_clock.elapsed();
        Logs.info(m =>
          m(
            "http: %s request to %s finished in %fms",
            request.request.meth |> method_to_string,
            request.request.target,
            Mtime.Span.abs_diff(start_request, end_request)
            |> Mtime.Span.to_ms,
          )
        );
        response;
      }
    );
  };
}