From 21b6e96891d8281b164e843e5195759eaae39817 Mon Sep 17 00:00:00 2001 From: Alp Mestanogullari Date: Sun, 19 Apr 2015 10:07:58 +0200 Subject: [PATCH] add a jsForAPI function that takes an API type proxy and generates js functions for each endpoint, collecting the result in a big String. fixes #12 --- CHANGELOG.md | 1 + src/Servant/JQuery.hs | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceac30d4..99eeaf5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ * Extend `HeaderArg` to support more advanced HTTP header handling (https://github.com/haskell-servant/servant-jquery/pull/6) * Support content-type aware combinators (but require that endpoints support JSON) * Add support for Matrix params (https://github.com/haskell-servant/servant-jquery/pull/11) +* Add functions that directly generate the Javascript code from the API type without having to manually pattern match on the result. 0.2.2 ----- diff --git a/src/Servant/JQuery.hs b/src/Servant/JQuery.hs index d979755d..22d13288 100644 --- a/src/Servant/JQuery.hs +++ b/src/Servant/JQuery.hs @@ -1,5 +1,6 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} +{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | @@ -12,14 +13,17 @@ module Servant.JQuery ( jquery , generateJS + , jsForAPI , printJS , module Servant.JQuery.Internal + , GenerateCode(..) ) where import Control.Lens import Data.List import Data.Monoid import Data.Proxy +import Servant.API import Servant.JQuery.Internal jquery :: HasJQ layout => Proxy layout -> JQ layout @@ -90,3 +94,24 @@ generateJS req = "\n" <> printJS :: AjaxReq -> IO () printJS = putStrLn . generateJS + +-- | Utility class used by 'jsForAPI' which will +-- directly hand you all the Javascript code +-- instead of handing you a ':<|>'-separated list +-- of 'AjaxReq' like 'jquery' and then having to +-- use 'generateJS' on each 'AjaxReq'. +class GenerateCode reqs where + jsFor :: reqs -> String + +instance GenerateCode AjaxReq where + jsFor = generateJS + +instance GenerateCode rest => GenerateCode (AjaxReq :<|> rest) where + jsFor (req :<|> rest) = jsFor req ++ jsFor rest + +-- | Directly generate all the javascript functions for your API +-- from a 'Proxy' for your API type. You can then write it to +-- a file or integrate it in a page, for example. +jsForAPI :: (HasJQ api, GenerateCode (JQ api)) + => Proxy api -> String +jsForAPI p = jsFor (jquery p)