Elm Url Query Pipeline

Hi Folks!

I found myself recently needing to parse a number url of query params. It was getting very messy and wished I had something more like elm-json-decode-pipeline.

I had query parsers that looked like this:

type alias AuthCallback =
    { userId : Int
    , userName : Maybe String
    , idToken : String
    , idTokenExpiresAt : Int
    , refreshToken : String
    }


authCallbackQueryOld : Query.Parser (Maybe AuthCallback)
authCallbackQueryOld =
    Query.map5
        (\maybeUserId userName maybeIdToken maybeIdTokenExpiresAt maybeRefreshToken ->
            Maybe.map4
                (\userId idToken idTokenExpiresAt refreshToken ->
                    { userId = userId
                    , userName = userName
                    , idToken = idToken
                    , idTokenExpiresAt = idTokenExpiresAt
                    , refreshToken = refreshToken
                    }
                )
                maybeUserId
                maybeIdToken
                maybeIdTokenExpiresAt
                maybeRefreshToken
        )
        (Query.int "user_id")
        (Query.string "user_name")
        (Query.string "id_token")
        (Query.int "id_token_expires_at")
        (Query.string "refresh_token")
        

They now look more like this:

import Url.Parser.Query as Query
import Url.Query.Pipeline as Pipeline


type alias AuthCallback =
    { userId : Int
    , userName : Maybe String
    , idToken : String
    , idTokenExpiresAt : Int
    , refreshToken : String
    }


authCallbackQuery : Query.Parser (Maybe AuthCallback)
authCallbackQuery =
    Pipeline.succeed AuthCallback
        |> Pipeline.required (Query.int "user_id")
        |> Pipeline.optional (Query.string "user_name")
        |> Pipeline.required (Query.string "id_token")
        |> Pipeline.required (Query.int "id_token_expires_at")
        |> Pipeline.required (Query.string "refresh_token")

I’ve published the helpers as a package in case anyone finds it useful

https://package.elm-lang.org/packages/andrewMacmurray/elm-url-query-pipeline/latest/

Feedback and thoughts are most welcome!

15 Likes

Thanks for sharing this Andrew

1 Like