{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts, AllowAmbiguousTypes, FlexibleInstances, IncoherentInstances, UndecidableInstances, PolyKinds, TypeInType, BlockArguments, DataKinds #-}

{-|
Module: IHP.Controller.Param
Description: Accessing query parameters and the request body
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.Controller.Param where

import IHP.Prelude
import qualified Data.Either as Either
import IHP.Controller.RequestContext
import qualified Network.Wai as Wai
import qualified Data.UUID as UUID
import qualified IHP.ModelSupport as ModelSupport
import qualified Data.ByteString.Char8 as Char8
import IHP.ValidationSupport
import GHC.TypeLits
import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec
import qualified GHC.Float as Float
import qualified Control.Exception as Exception
import IHP.Controller.Context
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.KeyMap as Aeson
import qualified Data.Aeson.Key as Aeson
import qualified Data.Scientific as Scientific
import qualified Data.Vector as Vector
import qualified Control.DeepSeq as DeepSeq
import Text.Read (readMaybe)

-- | 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
param :: (?context :: ControllerContext) => (ParamReader valueType) => ByteString -> valueType
param :: forall valueType.
(?context::ControllerContext, ParamReader valueType) =>
ByteString -> valueType
param !ByteString
name = case forall paramType.
(?context::ControllerContext, ParamReader paramType) =>
ByteString -> Either ParamException paramType
paramOrError ByteString
name of
        Left ParamException
exception -> forall a e. Exception e => e -> a
Exception.throw ParamException
exception
        Right valueType
value -> valueType
value
{-# INLINABLE param #-}

-- | 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
paramList :: forall valueType. (?context :: ControllerContext, DeepSeq.NFData valueType, ParamReader valueType) => ByteString -> [valueType]
paramList :: forall valueType.
(?context::ControllerContext, NFData valueType,
 ParamReader valueType) =>
ByteString -> [valueType]
paramList ByteString
name =
    (?context::ControllerContext) => [(ByteString, Maybe ByteString)]
allParams
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a. (a -> Bool) -> [a] -> [a]
filter (\(ByteString
paramName, Maybe ByteString
paramValue) -> ByteString
paramName forall a. Eq a => a -> a -> Bool
== ByteString
name)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (\(ByteString
paramName, Maybe ByteString
paramValue) -> Maybe ByteString
paramValue)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map (forall a. ParamReader a => ByteString -> Either ByteString a
readParameter @valueType)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map (forall b a. b -> Either a b -> b
Either.fromRight (forall a. Text -> a
error (forall {a} {a}.
(Semigroup a, IsString a, ConvertibleStrings a a) =>
a -> a
paramParserErrorMessage ByteString
name)))
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a. NFData a => a -> a
DeepSeq.force
{-# INLINABLE paramList #-}

-- | 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"
-- []
--
--
paramListOrNothing :: forall valueType. (?context :: ControllerContext, DeepSeq.NFData valueType, ParamReader valueType) => ByteString -> [Maybe valueType]
paramListOrNothing :: forall valueType.
(?context::ControllerContext, NFData valueType,
 ParamReader valueType) =>
ByteString -> [Maybe valueType]
paramListOrNothing ByteString
name =
    (?context::ControllerContext) => [(ByteString, Maybe ByteString)]
allParams
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a. (a -> Bool) -> [a] -> [a]
filter (\(ByteString
paramName, Maybe ByteString
paramValue) -> ByteString
paramName forall a. Eq a => a -> a -> Bool
== ByteString
name)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (\(ByteString
paramName, Maybe ByteString
paramValue) -> Maybe ByteString
paramValue)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map (\ByteString
paramValue -> if ByteString
paramValue forall a. Eq a => a -> a -> Bool
== ByteString
"" then forall a b. a -> Either a b
Left ByteString
"Empty ByteString" else forall a. ParamReader a => ByteString -> Either ByteString a
readParameter @valueType ByteString
paramValue)
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map (\Either ByteString valueType
value -> case Either ByteString valueType
value of
            Left ByteString
_ -> forall a. Maybe a
Nothing
            Right valueType
val -> forall a. a -> Maybe a
Just valueType
val
        )
    forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a. NFData a => a -> a
DeepSeq.force
{-# INLINABLE paramListOrNothing #-}

paramParserErrorMessage :: a -> a
paramParserErrorMessage a
name = a
"param: Parameter '" forall a. Semigroup a => a -> a -> a
<> forall a b. ConvertibleStrings a b => a -> b
cs a
name forall a. Semigroup a => a -> a -> a
<> a
"' is invalid"

-- | Thrown when a parameter is missing when calling 'param "myParam"' or related functions
data ParamException
    = ParamNotFoundException { ParamException -> ByteString
name :: ByteString }
    | ParamCouldNotBeParsedException { name :: ByteString, ParamException -> ByteString
parserError :: ByteString }
    deriving (Int -> ParamException -> ShowS
[ParamException] -> ShowS
ParamException -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ParamException] -> ShowS
$cshowList :: [ParamException] -> ShowS
show :: ParamException -> String
$cshow :: ParamException -> String
showsPrec :: Int -> ParamException -> ShowS
$cshowsPrec :: Int -> ParamException -> ShowS
Show, ParamException -> ParamException -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ParamException -> ParamException -> Bool
$c/= :: ParamException -> ParamException -> Bool
== :: ParamException -> ParamException -> Bool
$c== :: ParamException -> ParamException -> Bool
Eq)

instance Exception ParamException where
    displayException :: ParamException -> String
displayException (ParamNotFoundException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ParamException -> ByteString
name }) = String
"param: Parameter '" forall a. Semigroup a => a -> a -> a
<> forall a b. ConvertibleStrings a b => a -> b
cs ByteString
name forall a. Semigroup a => a -> a -> a
<> String
"' not found"
    displayException (ParamCouldNotBeParsedException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ParamException -> ByteString
name, ByteString
parserError :: ByteString
$sel:parserError:ParamNotFoundException :: ParamException -> ByteString
parserError }) = String
"param: Parameter '" forall a. Semigroup a => a -> a -> a
<> forall a b. ConvertibleStrings a b => a -> b
cs ByteString
name forall a. Semigroup a => a -> a -> a
<> String
"' could not be parsed, " forall a. Semigroup a => a -> a -> a
<> forall a b. ConvertibleStrings a b => a -> b
cs ByteString
parserError

-- | Specialized version of param for 'Text'.
--
-- This way you don't need to know about the type application syntax.
paramText :: (?context :: ControllerContext) => ByteString -> Text
paramText :: (?context::ControllerContext) => ByteString -> Text
paramText = forall valueType.
(?context::ControllerContext, ParamReader valueType) =>
ByteString -> valueType
param @Text

-- | Specialized version of param for 'Int'.
--
-- This way you don't need to know about the type application syntax.
paramInt :: (?context :: ControllerContext) => ByteString -> Int
paramInt :: (?context::ControllerContext) => ByteString -> Int
paramInt = forall valueType.
(?context::ControllerContext, ParamReader valueType) =>
ByteString -> valueType
param @Int

-- | Specialized version of param for 'Bool'.
--
-- This way you don't need to know about the type application syntax.
paramBool :: (?context :: ControllerContext) => ByteString -> Bool
paramBool :: (?context::ControllerContext) => ByteString -> Bool
paramBool = forall valueType.
(?context::ControllerContext, ParamReader valueType) =>
ByteString -> valueType
param @Bool

-- | Specialized version of param for 'UUID'.
--
-- This way you don't need to know about the type application syntax.
paramUUID :: (?context :: ControllerContext) => ByteString -> UUID
paramUUID :: (?context::ControllerContext) => ByteString -> UUID
paramUUID = forall valueType.
(?context::ControllerContext, ParamReader valueType) =>
ByteString -> valueType
param @UUID

-- | 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@
hasParam :: (?context :: ControllerContext) => ByteString -> Bool
hasParam :: (?context::ControllerContext) => ByteString -> Bool
hasParam = forall a. Maybe a -> Bool
isJust forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. (?context::ControllerContext) => ByteString -> Maybe ByteString
queryOrBodyParam
{-# INLINABLE hasParam #-}

-- | 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@.
paramOrDefault :: (?context :: ControllerContext) => ParamReader a => a -> ByteString -> a
paramOrDefault :: forall a.
(?context::ControllerContext, ParamReader a) =>
a -> ByteString -> a
paramOrDefault !a
defaultValue = forall a. a -> Maybe a -> a
fromMaybe a
defaultValue forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. forall paramType.
(?context::ControllerContext, ParamReader (Maybe paramType)) =>
ByteString -> Maybe paramType
paramOrNothing
{-# INLINABLE paramOrDefault #-}

-- | 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@.
paramOrNothing :: forall paramType. (?context :: ControllerContext) => ParamReader (Maybe paramType) => ByteString -> Maybe paramType
paramOrNothing :: forall paramType.
(?context::ControllerContext, ParamReader (Maybe paramType)) =>
ByteString -> Maybe paramType
paramOrNothing !ByteString
name =
    case forall paramType.
(?context::ControllerContext, ParamReader paramType) =>
ByteString -> Either ParamException paramType
paramOrError ByteString
name of
        Left ParamNotFoundException {} -> forall a. Maybe a
Nothing
        Left ParamException
otherException -> forall a e. Exception e => e -> a
Exception.throw ParamException
otherException
        Right Maybe paramType
value -> Maybe paramType
value
{-# INLINABLE paramOrNothing #-}

-- | Like 'param', but returns @Left "Some error message"@ if the parameter is missing or invalid
paramOrError :: forall paramType. (?context :: ControllerContext) => ParamReader paramType => ByteString -> Either ParamException paramType
paramOrError :: forall paramType.
(?context::ControllerContext, ParamReader paramType) =>
ByteString -> Either ParamException paramType
paramOrError !ByteString
name =
    let
        RequestContext { RequestBody
$sel:requestBody:RequestContext :: RequestContext -> RequestBody
requestBody :: RequestBody
requestBody } = ?context::ControllerContext
?context forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get forall a. IsLabel "requestContext" a => a
#requestContext
    in case RequestBody
requestBody of
        FormBody {} -> case (?context::ControllerContext) => ByteString -> Maybe ByteString
queryOrBodyParam ByteString
name of
                Just ByteString
value -> case forall a. ParamReader a => ByteString -> Either ByteString a
readParameter @paramType ByteString
value of
                    Left ByteString
parserError -> forall a b. a -> Either a b
Left ParamCouldNotBeParsedException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ByteString
name, ByteString
parserError :: ByteString
$sel:parserError:ParamNotFoundException :: ByteString
parserError }
                    Right paramType
value -> forall a b. b -> Either a b
Right paramType
value
                Maybe ByteString
Nothing -> forall a b. a -> Either a b
Left ParamNotFoundException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ByteString
name }
        JSONBody { Maybe Value
$sel:jsonPayload:FormBody :: RequestBody -> Maybe Value
jsonPayload :: Maybe Value
jsonPayload } -> case Maybe Value
jsonPayload of
                (Just (Aeson.Object Object
hashMap)) -> case forall v. Key -> KeyMap v -> Maybe v
Aeson.lookup (Text -> Key
Aeson.fromText forall a b. (a -> b) -> a -> b
$ forall a b. ConvertibleStrings a b => a -> b
cs ByteString
name) Object
hashMap of
                    Just Value
value -> case forall a. ParamReader a => Value -> Either ByteString a
readParameterJSON @paramType Value
value of
                        Left ByteString
parserError -> forall a b. a -> Either a b
Left ParamCouldNotBeParsedException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ByteString
name, ByteString
parserError :: ByteString
$sel:parserError:ParamNotFoundException :: ByteString
parserError }
                        Right paramType
value -> forall a b. b -> Either a b
Right paramType
value
                    Maybe Value
Nothing -> forall a b. a -> Either a b
Left ParamNotFoundException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ByteString
name }
                Maybe Value
_ -> forall a b. a -> Either a b
Left ParamNotFoundException { ByteString
name :: ByteString
$sel:name:ParamNotFoundException :: ByteString
name }
{-# INLINABLE paramOrError #-}

-- | Returns a parameter without any parsing. Returns @Nothing@ when the parameter is missing.
queryOrBodyParam :: (?context :: ControllerContext) => ByteString -> Maybe ByteString
queryOrBodyParam :: (?context::ControllerContext) => ByteString -> Maybe ByteString
queryOrBodyParam !ByteString
name = forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup ByteString
name (?context::ControllerContext) => [(ByteString, Maybe ByteString)]
allParams)
{-# INLINABLE queryOrBodyParam #-}

-- | Returns all params available in the current request
allParams :: (?context :: ControllerContext) => [(ByteString, Maybe ByteString)]
allParams :: (?context::ControllerContext) => [(ByteString, Maybe ByteString)]
allParams = case RequestBody
requestBody of
            FormBody { [Param]
$sel:params:FormBody :: RequestBody -> [Param]
params :: [Param]
params, [File ByteString]
$sel:files:FormBody :: RequestBody -> [File ByteString]
files :: [File ByteString]
files } -> forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [(forall a b. (a -> b) -> [a] -> [b]
map (\(ByteString
a, ByteString
b) -> (ByteString
a, forall a. a -> Maybe a
Just ByteString
b)) [Param]
params), (Request -> [(ByteString, Maybe ByteString)]
Wai.queryString Request
request)]
            JSONBody { Maybe Value
jsonPayload :: Maybe Value
$sel:jsonPayload:FormBody :: RequestBody -> Maybe Value
jsonPayload } -> forall a. Text -> a
error Text
"allParams: Not supported for JSON requests"
    where
        RequestContext { Request
$sel:request:RequestContext :: RequestContext -> Request
request :: Request
request, RequestBody
requestBody :: RequestBody
$sel:requestBody:RequestContext :: RequestContext -> RequestBody
requestBody } = ?context::ControllerContext
?context forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get forall a. IsLabel "requestContext" a => a
#requestContext

-- | 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.
class ParamReader a where
    -- | The error messages here should be human-readable, as they're visible e.g. in forms
    readParameter :: ByteString -> Either ByteString a
    -- | The error messages here are directed at other developers, so they can be a bit more technical than 'readParameter' errors
    readParameterJSON :: Aeson.Value -> Either ByteString a
    readParameterJSON = forall a. ParamReader a => Value -> Either ByteString a
enumParamReaderJSON

instance ParamReader ByteString where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString ByteString
readParameter ByteString
byteString = forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
byteString

    readParameterJSON :: Value -> Either ByteString ByteString
readParameterJSON (Aeson.String Text
bytestring) = forall a b. b -> Either a b
Right (forall a b. ConvertibleStrings a b => a -> b
cs Text
bytestring)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

instance ParamReader Int where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Int
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly ((forall a. Num a => Parser a -> Parser a
Attoparsec.signed forall a. Integral a => Parser a
Attoparsec.decimal) forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall t. Chunk t => Parser t ()
Attoparsec.endOfInput) ByteString
byteString of
            Right Int
value -> forall a b. b -> Either a b
Right Int
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be an integer"

    readParameterJSON :: Value -> Either ByteString Int
readParameterJSON (Aeson.Number Scientific
number) =
            case forall r i. (RealFloat r, Integral i) => Scientific -> Either r i
Scientific.floatingOrInteger Scientific
number of
                    Left Double
float -> forall a b. a -> Either a b
Left ByteString
"Expected Int"
                    Right Int
int -> forall a b. b -> Either a b
Right Int
int
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Int"

instance ParamReader Integer where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Integer
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly ((forall a. Num a => Parser a -> Parser a
Attoparsec.signed forall a. Integral a => Parser a
Attoparsec.decimal) forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall t. Chunk t => Parser t ()
Attoparsec.endOfInput) ByteString
byteString of
            Right Integer
value -> forall a b. b -> Either a b
Right Integer
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be an integer"

    readParameterJSON :: Value -> Either ByteString Integer
readParameterJSON (Aeson.Number Scientific
number) =
            case forall r i. (RealFloat r, Integral i) => Scientific -> Either r i
Scientific.floatingOrInteger Scientific
number of
                    Left Double
float -> forall a b. a -> Either a b
Left ByteString
"Expected Integer"
                    Right Integer
integer -> forall a b. b -> Either a b
Right Integer
integer
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Integer"

instance ParamReader Double where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Double
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly (Parser ByteString Double
Attoparsec.double forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall t. Chunk t => Parser t ()
Attoparsec.endOfInput) ByteString
byteString of
            Right Double
value -> forall a b. b -> Either a b
Right Double
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be a number with decimals"

    readParameterJSON :: Value -> Either ByteString Double
readParameterJSON (Aeson.Number Scientific
number) =
            case forall r i. (RealFloat r, Integral i) => Scientific -> Either r i
Scientific.floatingOrInteger Scientific
number of
                    Left Double
double -> forall a b. b -> Either a b
Right Double
double
                    Right Integer
integer -> forall a b. b -> Either a b
Right (forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
integer)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Double"

instance ParamReader Scientific.Scientific where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Scientific
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly (Parser ByteString Scientific
Attoparsec.scientific forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall t. Chunk t => Parser t ()
Attoparsec.endOfInput) ByteString
byteString of
            Right Scientific
value -> forall a b. b -> Either a b
Right Scientific
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be a number with decimals"

    readParameterJSON :: Value -> Either ByteString Scientific
readParameterJSON (Aeson.Number Scientific
number) = forall a b. b -> Either a b
Right Scientific
number
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Scientific"

instance ParamReader Float where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Float
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly (Parser ByteString Double
Attoparsec.double forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall t. Chunk t => Parser t ()
Attoparsec.endOfInput) ByteString
byteString of
            Right Double
value -> forall a b. b -> Either a b
Right (Double -> Float
Float.double2Float Double
value)
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be a number with decimals"

    readParameterJSON :: Value -> Either ByteString Float
readParameterJSON (Aeson.Number Scientific
number) =
            case forall r i. (RealFloat r, Integral i) => Scientific -> Either r i
Scientific.floatingOrInteger Scientific
number of
                    Left Float
double -> forall a b. b -> Either a b
Right Float
double
                    Right Integer
integer -> forall a b. b -> Either a b
Right (forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
integer)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Float"

instance ParamReader ModelSupport.Point where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Point
readParameter ByteString
byteString =
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly (do Double
x <- Parser ByteString Double
Attoparsec.double; Char -> Parser Char
Attoparsec.char Char
','; Double
y <- Parser ByteString Double
Attoparsec.double; forall t. Chunk t => Parser t ()
Attoparsec.endOfInput; forall (f :: * -> *) a. Applicative f => a -> f a
pure ModelSupport.Point { Double
$sel:x:Point :: Double
x :: Double
x, Double
$sel:y:Point :: Double
y :: Double
y }) ByteString
byteString of
            Right Point
value -> forall a b. b -> Either a b
Right Point
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be two numbers with a comma, e.g. '1,2'"

    readParameterJSON :: Value -> Either ByteString Point
readParameterJSON (Aeson.String Text
string) = let ByteString
byteString :: ByteString = forall a b. ConvertibleStrings a b => a -> b
cs Text
string in  forall a. ParamReader a => ByteString -> Either ByteString a
readParameter ByteString
byteString
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Point"

instance ParamReader ModelSupport.Polygon where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Polygon
readParameter ByteString
byteString =
        let
            pointParser :: Parser Point
pointParser = do
                Char -> Parser Char
Attoparsec.char Char
'('
                Double
x <- Parser ByteString Double
Attoparsec.double
                Char -> Parser Char
Attoparsec.char Char
','
                Double
y <- Parser ByteString Double
Attoparsec.double
                Char -> Parser Char
Attoparsec.char Char
')'
                forall (f :: * -> *) a. Applicative f => a -> f a
pure ModelSupport.Point { Double
y :: Double
x :: Double
$sel:y:Point :: Double
$sel:x:Point :: Double
.. }
            parser :: Parser ByteString Polygon
parser = do
                [Point]
points <- Parser Point
pointParser forall (f :: * -> *) a s. Alternative f => f a -> f s -> f [a]
`Attoparsec.sepBy` (Char -> Parser Char
Attoparsec.char Char
',')
                forall t. Chunk t => Parser t ()
Attoparsec.endOfInput
                forall (f :: * -> *) a. Applicative f => a -> f a
pure ModelSupport.Polygon { [Point]
$sel:points:Polygon :: [Point]
points :: [Point]
.. }
        in
        case forall a. Parser a -> ByteString -> Either String a
Attoparsec.parseOnly Parser ByteString Polygon
parser ByteString
byteString of
            Right Polygon
value -> forall a b. b -> Either a b
Right Polygon
value
            Left String
error -> forall a b. a -> Either a b
Left ByteString
"has to be points wrapped in parenthesis, separated with a comma, e.g. '(1,2),(3,4)'"

    readParameterJSON :: Value -> Either ByteString Polygon
readParameterJSON (Aeson.String Text
string) = let ByteString
byteString :: ByteString = forall a b. ConvertibleStrings a b => a -> b
cs Text
string in forall a. ParamReader a => ByteString -> Either ByteString a
readParameter ByteString
byteString
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Polygon"

instance ParamReader Text where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Text
readParameter ByteString
byteString = forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
byteString)

    readParameterJSON :: Value -> Either ByteString Text
readParameterJSON (Aeson.String Text
text) = forall a b. b -> Either a b
Right Text
text
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

-- | Parses comma separated input like @userIds=1,2,3@
--
-- __Example:__
--
-- >>> let userIds :: [Int] = param "userIds"
instance ParamReader value => ParamReader [value] where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString [value]
readParameter ByteString
byteString =
        ByteString
byteString
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> Char -> ByteString -> [ByteString]
Char8.split Char
','
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map forall a. ParamReader a => ByteString -> Either ByteString a
readParameter
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. [Either a b] -> ([a], [b])
Either.partitionEithers
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> \case
            ([], [value]
values) -> forall a b. b -> Either a b
Right [value]
values
            ((ByteString
first:[ByteString]
rest), [value]
_) -> forall a b. a -> Either a b
Left ByteString
first

    readParameterJSON :: Value -> Either ByteString [value]
readParameterJSON (Aeson.Array Array
values) =
        Array
values
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a. Vector a -> [a]
Vector.toList
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. (a -> b) -> [a] -> [b]
map forall a. ParamReader a => Value -> Either ByteString a
readParameterJSON
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> forall a b. [Either a b] -> ([a], [b])
Either.partitionEithers
        forall {t1} {t2}. t1 -> (t1 -> t2) -> t2
|> \case
            ([], [value]
values) -> forall a b. b -> Either a b
Right [value]
values
            ((ByteString
first:[ByteString]
rest), [value]
_) -> forall a b. a -> Either a b
Left ByteString
first
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Array"

-- | Parses a boolean.
--
-- Html form checkboxes usually use @on@ or @off@ for representation. These
-- values are supported here.
instance ParamReader Bool where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Bool
readParameter ByteString
on | ByteString
on forall a. Eq a => a -> a -> Bool
== forall a b. ConvertibleStrings a b => a -> b
cs (forall a. InputValue a => a -> Text
ModelSupport.inputValue Bool
True) = forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
    readParameter ByteString
true | Text -> Text
toLower (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
true) forall a. Eq a => a -> a -> Bool
== Text
"true" = forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
    readParameter ByteString
_ = forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False

    readParameterJSON :: Value -> Either ByteString Bool
readParameterJSON (Aeson.Bool Bool
bool) = forall a b. b -> Either a b
Right Bool
bool
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected Bool"

instance ParamReader UUID where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString UUID
readParameter ByteString
byteString =
        case ByteString -> Maybe UUID
UUID.fromASCIIBytes ByteString
byteString of
            Just UUID
uuid -> forall (f :: * -> *) a. Applicative f => a -> f a
pure UUID
uuid
            Maybe UUID
Nothing -> forall a b. a -> Either a b
Left ByteString
"has to be an UUID"

    readParameterJSON :: Value -> Either ByteString UUID
readParameterJSON (Aeson.String Text
string) =
        case Text -> Maybe UUID
UUID.fromText Text
string of
            Just UUID
uuid -> forall (f :: * -> *) a. Applicative f => a -> f a
pure UUID
uuid
            Maybe UUID
Nothing -> forall a b. a -> Either a b
Left ByteString
"Invalid UUID"
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String with an UUID"

-- | Accepts values such as @2020-11-08T12:03:35Z@ or @2020-11-08@
instance ParamReader UTCTime where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString UTCTime
readParameter ByteString
"" = forall a b. a -> Either a b
Left ByteString
"This field cannot be empty"
    readParameter ByteString
byteString =
        let
            input :: String
input = (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
byteString)
            dateTime :: Maybe UTCTime
dateTime = forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%m-%dT%H:%M:%S%QZ" String
input
            date :: Maybe UTCTime
date = forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%-m-%-d" String
input
        in case Maybe UTCTime
dateTime of
            Maybe UTCTime
Nothing -> case Maybe UTCTime
date of
                Just UTCTime
value -> forall a b. b -> Either a b
Right UTCTime
value
                Maybe UTCTime
Nothing -> forall a b. a -> Either a b
Left ByteString
"has to be a valid date and time, e.g. 2020-11-08T12:03:35Z"
            Just UTCTime
value -> forall a b. b -> Either a b
Right UTCTime
value

    readParameterJSON :: Value -> Either ByteString UTCTime
readParameterJSON (Aeson.String Text
string) = forall a. ParamReader a => ByteString -> Either ByteString a
readParameter (forall a b. ConvertibleStrings a b => a -> b
cs Text
string)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

-- | Accepts values such as @2020-11-08T12:03:35Z@ or @2020-11-08@
instance ParamReader LocalTime where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString LocalTime
readParameter ByteString
"" = forall a b. a -> Either a b
Left ByteString
"This field cannot be empty"
    readParameter ByteString
byteString =
        let
            input :: String
input = (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
byteString)
            dateTime :: Maybe LocalTime
dateTime = forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%m-%dT%H:%M:%S%QZ" String
input
            date :: Maybe LocalTime
date = forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%-m-%-d" String
input
        in case Maybe LocalTime
dateTime of
            Maybe LocalTime
Nothing -> case Maybe LocalTime
date of
                Just LocalTime
value -> forall a b. b -> Either a b
Right LocalTime
value
                Maybe LocalTime
Nothing -> forall a b. a -> Either a b
Left ByteString
"has to be a valid date and time, e.g. 2020-11-08T12:03:35Z"
            Just LocalTime
value -> forall a b. b -> Either a b
Right LocalTime
value

    readParameterJSON :: Value -> Either ByteString LocalTime
readParameterJSON (Aeson.String Text
string) = forall a. ParamReader a => ByteString -> Either ByteString a
readParameter (forall a b. ConvertibleStrings a b => a -> b
cs Text
string)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

-- | Accepts values such as @2020-11-08@
instance ParamReader Day where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString Day
readParameter ByteString
"" = forall a b. a -> Either a b
Left ByteString
"This field cannot be empty"
    readParameter ByteString
byteString =
        let
            input :: String
input = (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
byteString)
            date :: Maybe Day
date = forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%-m-%-d" String
input
        in case Maybe Day
date of
            Just Day
value -> forall a b. b -> Either a b
Right Day
value
            Maybe Day
Nothing -> forall a b. a -> Either a b
Left ByteString
"has to be a date, e.g. 2020-11-08"

    readParameterJSON :: Value -> Either ByteString Day
readParameterJSON (Aeson.String Text
string) = forall a. ParamReader a => ByteString -> Either ByteString a
readParameter (forall a b. ConvertibleStrings a b => a -> b
cs Text
string)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

instance ParamReader TimeOfDay where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString TimeOfDay
readParameter ByteString
"" = forall a b. a -> Either a b
Left ByteString
"This field cannot be empty"
    readParameter ByteString
byteString =
        let
            input :: String
input = (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
byteString)
        in case forall a. Read a => String -> Maybe a
readMaybe String
input of
            Just TimeOfDay
value -> forall a b. b -> Either a b
Right TimeOfDay
value
            Maybe TimeOfDay
Nothing -> forall a b. a -> Either a b
Left ByteString
"has to be time in the format hh:mm:ss"

    readParameterJSON :: Value -> Either ByteString TimeOfDay
readParameterJSON (Aeson.String Text
string) = forall a. ParamReader a => ByteString -> Either ByteString a
readParameter (forall a b. ConvertibleStrings a b => a -> b
cs Text
string)
    readParameterJSON Value
_ = forall a b. a -> Either a b
Left ByteString
"Expected String"

instance {-# OVERLAPS #-} (ParamReader (ModelSupport.PrimaryKey model')) => ParamReader (ModelSupport.Id' model') where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString (Id' model')
readParameter ByteString
uuid = forall (table :: Symbol). PrimaryKey table -> Id' table
ModelSupport.Id forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. ParamReader a => ByteString -> Either ByteString a
readParameter ByteString
uuid
    readParameterJSON :: Value -> Either ByteString (Id' model')
readParameterJSON Value
value = forall (table :: Symbol). PrimaryKey table -> Id' table
ModelSupport.Id forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. ParamReader a => Value -> Either ByteString a
readParameterJSON Value
value

instance ParamReader param => ParamReader (Maybe param) where
    {-# INLINABLE readParameter #-}
    readParameter :: ByteString -> Either ByteString (Maybe param)
readParameter ByteString
param =
        case (forall a. ParamReader a => ByteString -> Either ByteString a
readParameter ByteString
param) :: Either ByteString param of
            Right param
value -> forall a b. b -> Either a b
Right (forall a. a -> Maybe a
Just param
value)
            Left ByteString
error | ByteString
param forall a. Eq a => a -> a -> Bool
== ByteString
"" -> forall a b. b -> Either a b
Right forall a. Maybe a
Nothing
            Left ByteString
error -> forall a b. a -> Either a b
Left ByteString
error

    readParameterJSON :: Value -> Either ByteString (Maybe param)
readParameterJSON Value
value =
        case (forall a. ParamReader a => Value -> Either ByteString a
readParameterJSON Value
value) :: Either ByteString param of
            Right param
value -> forall a b. b -> Either a b
Right (forall a. a -> Maybe a
Just param
value)
            Left ByteString
error | Value
value forall a. Eq a => a -> a -> Bool
== (Text -> Value
Aeson.String Text
"") -> forall a b. b -> Either a b
Right forall a. Maybe a
Nothing
            Left ByteString
error -> forall a b. a -> Either a b
Left ByteString
error

-- | 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 (TypeError ('Text ("Use 'let x = param \"..\"' instead of 'x <- param \"..\"'" :: Symbol))) => ParamReader  (IO param) where
    readParameter :: ByteString -> Either ByteString (IO param)
readParameter ByteString
_ = forall a. Text -> a
error Text
"Unreachable"
    readParameterJSON :: Value -> Either ByteString (IO param)
readParameterJSON Value
_ = forall a. Text -> a
error Text
"Unreachable"

-- | 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
enumParamReader :: forall parameter. (Enum parameter, ModelSupport.InputValue parameter) => ByteString -> Either ByteString parameter
enumParamReader :: forall parameter.
(Enum parameter, InputValue parameter) =>
ByteString -> Either ByteString parameter
enumParamReader ByteString
string =
        case forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\parameter
value -> forall a. InputValue a => a -> Text
ModelSupport.inputValue parameter
value forall a. Eq a => a -> a -> Bool
== Text
string') forall enumType. Enum enumType => [enumType]
allEnumValues of
            Just parameter
value -> forall a b. b -> Either a b
Right parameter
value
            Maybe parameter
Nothing -> forall a b. a -> Either a b
Left ByteString
"Invalid value"
    where
        string' :: Text
string' = forall a b. ConvertibleStrings a b => a -> b
cs ByteString
string

-- | Used as a default implementation for 'readParameterJSON'
--
-- __Example:__
--
-- > data Color = Yellow | Red | Blue deriving (Enum)
-- >
-- > instance ParamReader Color where
-- >     readParameter = enumParamReader
-- >     readParameterJSON = enumParamReaderJSON
enumParamReaderJSON :: forall parameter. (ParamReader parameter) => Aeson.Value -> Either ByteString parameter
enumParamReaderJSON :: forall a. ParamReader a => Value -> Either ByteString a
enumParamReaderJSON (Aeson.String Text
string) = forall a. ParamReader a => ByteString -> Either ByteString a
readParameter (forall a b. ConvertibleStrings a b => a -> b
cs Text
string)
enumParamReaderJSON Value
otherwise = forall a b. a -> Either a b
Left ByteString
"enumParamReaderJSON: Invalid value, expected a string but got something else"

-- | 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.
class FillParams (params :: [Symbol]) record where
    fill :: (
        ?context :: ControllerContext
        , HasField "meta" record ModelSupport.MetaBag
        , SetField "meta" record ModelSupport.MetaBag
        ) => record -> record

instance FillParams ('[]) record where
    fill :: (?context::ControllerContext, HasField "meta" record MetaBag,
 SetField "meta" record MetaBag) =>
record -> record
fill !record
record = record
record
    {-# INLINABLE fill #-}

instance (FillParams rest record
    , KnownSymbol fieldName
    , SetField fieldName record fieldType
    , ParamReader fieldType
    , HasField "meta" record ModelSupport.MetaBag
    , SetField "meta" record ModelSupport.MetaBag
    ) => FillParams (fieldName:rest) record where
    fill :: (?context::ControllerContext, HasField "meta" record MetaBag,
 SetField "meta" record MetaBag) =>
record -> record
fill !record
record = do
        let ByteString
name :: ByteString = forall a b. ConvertibleStrings a b => a -> b
cs forall a b. (a -> b) -> a -> b
$! (forall (n :: Symbol) (proxy :: Symbol -> *).
KnownSymbol n =>
proxy n -> String
symbolVal (forall {k} (t :: k). Proxy t
Proxy @fieldName))
        case forall paramType.
(?context::ControllerContext, ParamReader paramType) =>
ByteString -> Either ParamException paramType
paramOrError ByteString
name of
            Right !(fieldType
value :: fieldType) -> forall (params :: [Symbol]) record.
(FillParams params record, ?context::ControllerContext,
 HasField "meta" record MetaBag, SetField "meta" record MetaBag) =>
record -> record
fill @rest (forall (field :: Symbol) model value.
SetField field model value =>
value -> model -> model
setField @fieldName fieldType
value record
record)
            Left ParamCouldNotBeParsedException { ByteString
parserError :: ByteString
$sel:parserError:ParamNotFoundException :: ParamException -> ByteString
parserError } -> forall (params :: [Symbol]) record.
(FillParams params record, ?context::ControllerContext,
 HasField "meta" record MetaBag, SetField "meta" record MetaBag) =>
record -> record
fill @rest (forall (field :: Symbol) model.
(KnownSymbol field, HasField "meta" model MetaBag,
 SetField "meta" model MetaBag) =>
Proxy field -> Text -> model -> model
attachFailure (forall {k} (t :: k). Proxy t
Proxy @fieldName) (forall a b. ConvertibleStrings a b => a -> b
cs ByteString
parserError) record
record)
            Left ParamNotFoundException {} -> forall (params :: [Symbol]) record.
(FillParams params record, ?context::ControllerContext,
 HasField "meta" record MetaBag, SetField "meta" record MetaBag) =>
record -> record
fill @rest record
record
    {-# INLINABLE fill #-}

ifValid :: (HasField "meta" model ModelSupport.MetaBag) => (Either model model -> IO r) -> model -> IO r
ifValid :: forall model r.
HasField "meta" model MetaBag =>
(Either model model -> IO r) -> model -> IO r
ifValid Either model model -> IO r
branch model
model = Either model model -> IO r
branch ((if forall mono. MonoFoldable mono => mono -> Bool
null [(Text, Violation)]
annotations then forall a b. b -> Either a b
Right else forall a b. a -> Either a b
Left) model
model)
    where
        annotations :: [(Text, ModelSupport.Violation)]
        annotations :: [(Text, Violation)]
annotations = forall {k} (x :: k) r a. HasField x r a => r -> a
getField @"annotations" MetaBag
meta
        meta :: ModelSupport.MetaBag
        meta :: MetaBag
meta = forall {k} (x :: k) r a. HasField x r a => r -> a
getField @"meta" model
model

ifNew :: forall record. (?context :: ControllerContext, ?modelContext :: ModelSupport.ModelContext, HasField "meta" record MetaBag) => (record -> record) -> record -> record
ifNew :: forall record.
(?context::ControllerContext, ?modelContext::ModelContext,
 HasField "meta" record MetaBag) =>
(record -> record) -> record -> record
ifNew record -> record
thenBlock record
record = if forall model. HasField "meta" model MetaBag => model -> Bool
ModelSupport.isNew record
record then record -> record
thenBlock record
record else record
record


-- | 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
emptyValueToNothing :: Proxy name -> model -> model
emptyValueToNothing Proxy name
field = forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value,
 SetField name model value) =>
Proxy name -> (value -> value) -> model -> model
modify Proxy name
field (forall b a. b -> (a -> b) -> Maybe a -> b
maybe forall a. Maybe a
Nothing (\mono
value -> if forall mono. MonoFoldable mono => mono -> Bool
null mono
value then forall a. Maybe a
Nothing else forall a. a -> Maybe a
Just mono
value))