eberfreitas/elm-express/2.0.0

NOTE: the latest version is 3.0.0

Express.Middleware

This module exposes a very simple middleware system.

Types

type alias Middleware ctx msg =
ctx -> Request -> Response -> ( Response, Cmd msg )

Middlewares are simple functions that will receive your application's context, a request and a response as parameters, and return a response and command. Remember that you can lock a response inside your middlewares. To better understand what is a locked response, please refer to the Express.Response module documentation.

authMiddleware context request response =
    case Express.Request.cookie "user" request of
        Just _ ->
            ( response, Cmd.none )


        Nothing ->
            let
                newResponse =
                    response |> Express.Response.redirect "/login"
            in
            ( newResponse, newResponse |> Response.send request |> responsePort )

Running middlewares

run :
ctx
-> Request
-> List (Middleware ctx msg)
-> ( Response, Cmd msg )

Given a list of middleware functions, you can run them all in sequence by using the run function. Think of this function as a reducer or folding function that will aggregate the transformations from all middlewares into a single ( response, command ) tuple.

let
    middlewares =
        [ flashMsgMiddleware, authMiddleware ]
in
( newResponse, newCmd ) =
    run context request response middlewares