packages feed

morley-client-0.2.0: src/Morley/Client/RPC/QueryFixedParam.hs

-- SPDX-FileCopyrightText: 2021 Oxhead Alpha
-- SPDX-License-Identifier: LicenseRef-MIT-OA

module Morley.Client.RPC.QueryFixedParam
  ( QueryFixedParam
  ) where

import Data.ByteString.Builder qualified as Builder
import Data.ByteString.Lazy qualified as LBS
import Servant.API (ToHttpApiData(..), type (:>))
import Servant.Client.Core (HasClient(..), appendToQueryString)

import Morley.Util.TypeLits (KnownSymbol, Symbol, symbolValT')

-- | Like servant's @QueryParam@, but the value is fixed as a
-- type-level string.
data QueryFixedParam (name :: Symbol) (value :: Symbol)

instance (KnownSymbol sym, KnownSymbol val, HasClient m api)
      => HasClient m (QueryFixedParam sym val :> api) where

  type Client m (QueryFixedParam sym val :> api) = Client m api

  clientWithRoute pm Proxy req =
    clientWithRoute pm (Proxy :: Proxy api)
      $ appendToQueryString pname (Just $ encodeQueryParamValue pval) req
    where
      pname = symbolValT' @sym
      pval  = symbolValT' @val
      -- Lifted from the unreleased https://github.com/haskell-servant/servant/pull/1549
      encodeQueryParamValue = LBS.toStrict . Builder.toLazyByteString . toEncodedUrlPiece

  hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl