IHP Api Reference
Copyright(c) digitally induced GmbH 2020
Safe HaskellNone

IHP.Controller.Param

Description

 
Synopsis

Documentation

param :: (?context :: ControllerContext, 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

paramList :: (?context :: ControllerContext, 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 :: (?context :: ControllerContext, 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"
[]

data ParamException Source #

Thrown when a parameter is missing when calling 'param "myParam"' or related functions

paramText :: (?context :: ControllerContext) => ByteString -> Text Source #

Specialized version of param for Text.

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

paramInt :: (?context :: ControllerContext) => ByteString -> Int Source #

Specialized version of param for Int.

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

paramBool :: (?context :: ControllerContext) => ByteString -> Bool Source #

Specialized version of param for Bool.

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

paramUUID :: (?context :: ControllerContext) => ByteString -> UUID Source #

Specialized version of param for UUID.

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

hasParam :: (?context :: ControllerContext) => 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

paramOrDefault :: (?context :: ControllerContext, 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.

paramOrNothing :: (?context :: ControllerContext, 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.

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

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

queryOrBodyParam :: (?context :: ControllerContext) => ByteString -> Maybe ByteString Source #

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

allParams :: (?context :: ControllerContext) => [(ByteString, Maybe ByteString)] Source #

Returns all params available in the current request

class ParamReader a where Source #

Input parser for param.

Parses the input bytestring. Returns Left "some error" when there is an error parsing the value. Returns Right value when the parsing succeeded.

Minimal complete definition

readParameter

Methods

readParameter :: ByteString -> Either ByteString a Source #

The error messages here should be human-readable, as they're visible e.g. in forms

readParameterJSON :: Value -> Either ByteString a Source #

The error messages here are directed at other developers, so they can be a bit more technical than readParameter errors

Instances

Instances details
ParamReader ByteString 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 PGInterval Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader OrderByClause Source # 
Instance details

Defined in IHP.DataSync.REST.Controller

ParamReader SelectedColumns Source # 
Instance details

Defined in IHP.DataSync.REST.Controller

ParamReader JobStatus Source # 
Instance details

Defined in IHP.Job.Queue

ParamReader Scientific Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Text Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Day Source #

Accepts values such as 2020-11-08

Instance details

Defined in IHP.Controller.Param

ParamReader UTCTime Source #

Accepts values such as 2020-11-08T12:03:35Z or 2020-11-08

Instance details

Defined in IHP.Controller.Param

ParamReader LocalTime Source #

Accepts values such as 2020-11-08T12:03:35Z or 2020-11-08

Instance details

Defined in IHP.Controller.Param

ParamReader TimeOfDay Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader UUID Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Integer Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Bool Source #

Parses a boolean.

Html form checkboxes usually use on or off for representation. These values are supported here.

Instance details

Defined in IHP.Controller.Param

ParamReader Double Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Float Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader Int Source # 
Instance details

Defined in IHP.Controller.Param

(TypeError ('Text "Use 'let x = param \"..\"' instead of 'x <- param \"..\"'") :: Constraint) => ParamReader (IO param) Source #

Custom error hint when the param is called with do-notation

Example:

action Example = do
    myParam <- param "hello"

Now a custom type error will be shown telling the user to use let myParam = param "hello" instead of do-notation.

Instance details

Defined in IHP.Controller.Param

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

Defined in IHP.Controller.Param

ParamReader param => ParamReader (Maybe param) Source # 
Instance details

Defined in IHP.Controller.Param

ParamReader value => ParamReader [value] Source #

Parses comma separated input like userIds=1,2,3

Example:

>>> let userIds :: [Int] = param "userIds"
Instance details

Defined in IHP.Controller.Param

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

enumParamReaderJSON :: ParamReader parameter => Value -> Either ByteString parameter Source #

Used as a default implementation for readParameterJSON

Example:

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

instance ParamReader Color where
    readParameter = enumParamReader
    readParameterJSON = enumParamReaderJSON

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 :: (?context :: ControllerContext, ?modelContext :: ModelContext, HasField "meta" record MetaBag) => (record -> record) -> record -> record Source #

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