ihp-1.4.0: Haskell Web Framework
Copyright(c) digitally induced GmbH 2020
Safe HaskellNone
LanguageGHC2021

IHP.Controller.Param

Description

This module provides IHP-style parameter parsing using implicit parameters. It wraps the generic functionality from Wai.Request.Params with IHP's implicit ?request convention and adds IHP-specific ParamReader instances.

Synopsis

Reading parameters (implicit param versions)

param :: (?request :: Request, ParamReader valueType) => ByteString -> valueType Source #

Returns a query or body parameter from the current request. The raw string value is parsed before returning it. So the return value type depends on what you expect (e.g. can be Int, Text, UUID, Bool, some custom type).

When the parameter is missing or cannot be parsed, an exception is thrown and the current action is aborted. Use paramOrDefault when you want to get a default value instead of an exception, or paramOrNothing to get Nothing when the parameter is missing.

You can define a custom parameter parser by defining a ParamReader instance.

Example: Accessing a query parameter.

Let's say the request is:

GET /UsersAction?maxItems=50

We can read maxItems like this:

action UsersAction = do
    let maxItems :: Int = param "maxItems"

Example: Working with forms (Accessing a body parameter).

Let's say we have the following html form:

<form method="POST" action="/HelloWorld"
    <input type="text" name="firstname" placeholder="Your firstname" />
    <button type="submit">Send</button>
</form>

The form has firstname text field and a send button. When the form is submitted, it's send to /HelloWorld.

The following action reads the value of the submitted firstname and prints out Hello firstname:

action HelloWorldAction = do
    let firstname = param "firstname"
    renderPlain ("Hello " <> firstname)

Example: Missing parameters

Let's say the request is:

GET /HelloWorldAction

But the action requires us to provide a firstname, like:

action HelloWorldAction = do
    let firstname = param "firstname"
    renderPlain ("Hello " <> firstname)

Running the request GET /HelloWorldAction without the firstname parameter will cause an ParamNotFoundException to be thrown with:

param: Parameter 'firstname' not found

paramOrNothing :: (?request :: Request, ParamReader (Maybe paramType)) => ByteString -> Maybe paramType Source #

Like param, but returns Nothing the parameter is missing instead of throwing an exception.

Use paramOrDefault when you want to deal with a default value.

Example:

When calling GET /Users the variable page will be set to Nothing.

action UsersAction = do
    let page :: Maybe Int = paramOrNothing "page"

When calling GET /Users?page=1 the variable page will be set to Just 1.

paramOrDefault :: (?request :: Request, ParamReader a) => a -> ByteString -> a Source #

Like param, but returns a default value when the parameter is missing instead of throwing an exception.

Use paramOrNothing when you want to get Maybe.

Example: Pagination

When calling GET /Users the variable page will be set to the default value 0.

action UsersAction = do
    let page :: Int = paramOrDefault 0 "page"

When calling GET /Users?page=1 the variable page will be set to 1.

paramOrError :: (?request :: Request, ParamReader paramType) => ByteString -> Either ParamException paramType Source #

Like param, but returns Left "Some error message" if the parameter is missing or invalid

paramList :: (?request :: Request, NFData valueType, ParamReader valueType) => ByteString -> [valueType] Source #

Similiar to param but works with multiple params. Useful when working with checkboxes.

Given a query like:

ingredients=milk&ingredients=egg

This will return:

>>> paramList @Text "ingredients"
["milk", "egg"]

When no parameter with the name is given, an empty list is returned:

>>> paramList @Text "not_given_in_url"
[]

When a value cannot be parsed, this function will fail similiar to param.

Related: https://stackoverflow.com/questions/63875081/how-can-i-pass-list-params-in-ihp-forms/63879113

paramListOrNothing :: (?request :: Request, NFData valueType, ParamReader valueType) => ByteString -> [Maybe valueType] Source #

Similiar to paramOrNothing but works with multiple params. This is useful when submitting multiple input fields with the same name, and some may be empty.

Given a query like (note the ingredients in the middle that has no value):

ingredients=milk&ingredients&ingredients=egg

This will return:

>>> paramListOrNothing @Text "ingredients"
[Just "milk", Nothing, Just "egg"]

When no parameter with the name is given, an empty list is returned:

>>> paramListOrNothing @Text "not_given_in_url"
[]

hasParam :: (?request :: Request) => ByteString -> Bool Source #

Returns True when a parameter is given in the request via the query or request body.

Use paramOrDefault when you want to use this for providing a default value.

Example:

Given the request GET /HelloWorld

action HelloWorldAction = do
    if hasParam "firstname"
        then ...
        else renderPlain "Please provide your firstname"

This will render Please provide your firstname because hasParam "firstname" returns False

queryOrBodyParam :: (?request :: Request) => ByteString -> Maybe ByteString Source #

Returns a parameter without any parsing. Returns Nothing when the parameter is missing.

allParams :: (?request :: Request) => [(ByteString, Maybe ByteString)] Source #

Returns all params available in the current request

Specialized param functions

paramText :: (?request :: Request) => ByteString -> Text Source #

Specialized version of param for Text.

This way you don't need to know about the type application syntax.

paramInt :: (?request :: Request) => ByteString -> Int Source #

Specialized version of param for Int.

This way you don't need to know about the type application syntax.

paramBool :: (?request :: Request) => ByteString -> Bool Source #

Specialized version of param for Bool.

This way you don't need to know about the type application syntax.

paramUUID :: (?request :: Request) => ByteString -> UUID Source #

Specialized version of param for UUID.

This way you don't need to know about the type application syntax.

ParamReader typeclass (re-exported from Wai.Request.Params)

class ParamReader a where #

Minimal complete definition

readParameter

Instances

Instances details
ParamReader ByteString 
Instance details

Defined in Wai.Request.Params

ParamReader JobStatus Source # 
Instance details

Defined in IHP.Job.Queue

ParamReader Inet Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Interval Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Point Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Polygon Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Scientific 
Instance details

Defined in Wai.Request.Params

ParamReader Text 
Instance details

Defined in Wai.Request.Params

ParamReader Day 
Instance details

Defined in Wai.Request.Params

ParamReader UTCTime 
Instance details

Defined in Wai.Request.Params

ParamReader LocalTime 
Instance details

Defined in Wai.Request.Params

ParamReader TimeOfDay 
Instance details

Defined in Wai.Request.Params

ParamReader UUID 
Instance details

Defined in Wai.Request.Params

ParamReader Integer 
Instance details

Defined in Wai.Request.Params

ParamReader Bool 
Instance details

Defined in Wai.Request.Params

ParamReader Double 
Instance details

Defined in Wai.Request.Params

ParamReader Float 
Instance details

Defined in Wai.Request.Params

ParamReader Int 
Instance details

Defined in Wai.Request.Params

(TypeError ('Text "Use 'let x = param requestBody request \"..\"' instead of 'x <- param requestBody request \"..\"'") :: Constraint) => ParamReader (IO param) 
Instance details

Defined in Wai.Request.Params

ParamReader (PrimaryKey model') => ParamReader (Id' model') Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader param => ParamReader (Maybe param) 
Instance details

Defined in Wai.Request.Params

ParamReader value => ParamReader [value] 
Instance details

Defined in Wai.Request.Params

Exceptions (re-exported from Wai.Request.Params)

Helper functions for custom ParamReader instances

enumParamReader :: (Enum parameter, InputValue parameter) => ByteString -> Either ByteString parameter Source #

Can be used as a default implementation for readParameter for enum structures

Example:

data Color = Yellow | Red | Blue deriving (Enum)

instance ParamReader Color where
    readParameter = enumParamReader
    readParameterJSON = enumParamReaderJSON

Form filling

class FillParams (params :: [Symbol]) record where Source #

Provides the fill function for mass-assignment of multiple parameters to a record

Accepts a type-level list of parameter names (type-list syntax is like @'["a", "b", "c"]) and a record. Then each parameter is read from the request using the param API. The parameter value is written to the record field. Because the parameter is assigned to the record, the parameter name list can only contain attribute names of the record.

When there is a parser error, the error will be attached as a validation error to the record. The remaining parameters will continue to be read.

If a parameter is missing from the request, this will be ignored and the function proceeds as usual.

Example:

action UpdateUserAction { userId } = do
    user :: User <- fetch userId
    user
        |> fill @["firstname", "lastname", "email"]

This code will read the firstname, lastname and email from the request and assign them to the user.

Methods

fill :: record -> record Source #

Instances

Instances details
FillParams ('[] :: [Symbol]) record Source # 
Instance details

Defined in IHP.Controller.Param

Methods

fill :: record -> record Source #

(FillParams rest record, KnownSymbol fieldName, SetField fieldName record fieldType, ParamReader fieldType, HasField "meta" record MetaBag, SetField "meta" record MetaBag) => FillParams (fieldName ': rest) record Source # 
Instance details

Defined in IHP.Controller.Param

Methods

fill :: record -> record Source #

ifValid :: HasField "meta" model MetaBag => (Either model model -> IO r) -> model -> IO r Source #

ifNew :: (?modelContext :: ModelContext, HasField "meta" record MetaBag) => (record -> record) -> record -> record Source #

Utilities

emptyValueToNothing :: forall {name :: Symbol} {model} {mono}. (KnownSymbol name, HasField name model (Maybe mono), SetField name model (Maybe mono), MonoFoldable mono) => Proxy name -> model -> model Source #

Transforms Just "" to Nothing

Example: We have record called Company with a optional field comment :: Maybe Text

When we have a form that submits the comment field and the field is empty, it will not be NULL inside the database, instead it will be set to the empty string. To avoid this we can apply emptyValueToNothing #comment. This function turns the empty string into a Nothing value.

action UpdateCompanyAction { companyId } = do
    company <- fetch companyId
    company
        |> fill '["name", "comment"]
        |> emptyValueToNothing #comment
        |> updateRecord

Orphan instances