@@ -1,9 +1,7 @@
1# Generating Javascript functions to query an API
1# Generating Javascript functions to query an API
3−We will now see how *servant* lets you turn an API type into javascript
3+We will now see how **servant** lets you turn an API type into javascript
4−functions that you can call to query a webservice. The derived code assumes you
4+functions that you can call to query a webservice.
5−use *jQuery* but you could very easily adapt the code to generate ajax requests
6−based on vanilla javascript or another library than *jQuery*.
8For this, we will consider a simple page divided in two parts. At the top, we
6For this, we will consider a simple page divided in two parts. At the top, we
9will have a search box that lets us search in a list of Haskell books by
7will have a search box that lets us search in a list of Haskell books by
@@ -32,10 +30,11 @@ import Data.Aeson
32import Data.Proxy
30import Data.Proxy
33import Data.Text as T (Text)
31import Data.Text as T (Text)
34import Data.Text.IO as T (writeFile, readFile)
32import Data.Text.IO as T (writeFile, readFile)
35−import qualified Data.Text as T
36import GHC.Generics
33import GHC.Generics
37import Language.Javascript.JQuery
34import Language.Javascript.JQuery
38import Network.Wai
35import Network.Wai
36+import Network.Wai.Handler.Warp
37+import qualified Data.Text as T
39import Servant
38import Servant
40import Servant.JS
39import Servant.JS
41import System.Random
40import System.Random
@@ -78,7 +77,8 @@ book :: Text -> Text -> Int -> Book
78book = Book
77book = Book
81−We need a "book database". For the purpose of this guide, let's restrict ourselves to the following books.
80+We need a "book database". For the purpose of this guide, let's restrict
81+ourselves to the following books.
83``` haskell
83``` haskell
84books :: [Book]
84books :: [Book]
@@ -92,7 +92,10 @@ books =
95−Now, given an optional search string `q`, we want to perform a case insensitive search in that list of books. We're obviously not going to try and implement the best possible algorithm, this is out of scope for this tutorial. The following simple linear scan will do, given how small our list is.
95+Now, given an optional search string `q`, we want to perform a case insensitive
96+search in that list of books. We're obviously not going to try and implement
97+the best possible algorithm, this is out of scope for this tutorial. The
98+following simple linear scan will do, given how small our list is.
97``` haskell
100``` haskell
98searchBook :: Monad m => Maybe Text -> m (Search Book)
101searchBook :: Monad m => Maybe Text -> m (Search Book)
@@ -106,7 +109,9 @@ searchBook (Just q) = return (mkSearch q books')
106 q' = T.toLower q
109 q' = T.toLower q
109−We also need an endpoint that generates random points `(x, y)` with `-1 <= x,y <= 1`. The code below uses [random](http://hackage.haskell.org/package/random)'s `System.Random`.
112+We also need an endpoint that generates random points `(x, y)` with `-1 <= x,y
113+<= 1`. The code below uses
114+[random](http://hackage.haskell.org/package/random)'s `System.Random`.
111``` haskell
116``` haskell
112randomPoint :: MonadIO m => m Point
117randomPoint :: MonadIO m => m Point
@@ -131,54 +136,93 @@ server = randomPoint
132server' :: Server API'
137server' :: Server API'
133server' = server
138server' = server
134− :<|> serveDirectory "tutorial/t9"
139+ :<|> serveDirectory "static"
136app :: Application
141app :: Application
137app = serve api' server'
142app = serve api' server'
148+Why two different API types, proxies and servers though? Simply because we
140−Why two different API types, proxies and servers though? Simply because we don't want to generate javascript functions for the `Raw` part of our API type, so we need a `Proxy` for our API type `API'` without its `Raw` endpoint.
149+don't want to generate javascript functions for the `Raw` part of our API type,
150+so we need a `Proxy` for our API type `API'` without its `Raw` endpoint.
142−Very similarly to how one can derive haskell functions, we can derive the javascript with just a simple function call to `jsForAPI` from `Servant.JQuery`.
152+Very similarly to how one can derive haskell functions, we can derive the
153+javascript with just a simple function call to `jsForAPI` from
144``` haskell
156``` haskell
145apiJS :: Text
157apiJS :: Text
146apiJS = jsForAPI api vanillaJS
158apiJS = jsForAPI api vanillaJS
149−This `String` contains 2 Javascript functions:
161+This `Text` contains 2 Javascript functions, 'getPoint' and 'getBooks':
151``` javascript
163``` javascript
153−function getpoint(onSuccess, onError)
164+var getPoint = function(onSuccess, onError)
155− $.ajax(
166+ var xhr = new XMLHttpRequest();
156− { url: '/point'
167+ xhr.open('GET', '/point', true);
157− , success: onSuccess
168+ xhr.setRequestHeader("Accept","application/json");
169+ xhr.onreadystatechange = function (e) {
170+ if (xhr.readyState == 4) {
171+ if (xhr.status == 204 || xhr.status == 205) {
173+ } else if (xhr.status >= 200 && xhr.status < 300) {
174+ var value = JSON.parse(xhr.responseText);
177+ var value = JSON.parse(xhr.responseText);
158− , error: onError
178+ onError(value);
159− , method: 'GET'
179+ }
163−function getbooks(q, onSuccess, onError)
185+var getBooks = function(q, onSuccess, onError)
165− $.ajax(
187+ var xhr = new XMLHttpRequest();
166− { url: '/books' + '?q=' + encodeURIComponent(q)
188+ xhr.open('GET', '/books' + '?q=' + encodeURIComponent(q), true);
167− , success: onSuccess
189+ xhr.setRequestHeader("Accept","application/json");
190+ xhr.onreadystatechange = function (e) {
191+ if (xhr.readyState == 4) {
192+ if (xhr.status == 204 || xhr.status == 205) {
194+ } else if (xhr.status >= 200 && xhr.status < 300) {
195+ var value = JSON.parse(xhr.responseText);
198+ var value = JSON.parse(xhr.responseText);
168− , error: onError
199+ onError(value);
169− , method: 'GET'
200+ }
174−Right before starting up our server, we will need to write this `String` to a file, say `api.js`, along with a copy of the *jQuery* library, as provided by the [js-jquery](http://hackage.haskell.org/package/js-jquery) package.
207+We created a directory `static` that contains two static files: `index.html`,
208+which is the entrypoint to our little web application; and `ui.js`, which
209+contains some hand-written javascript. This javascript code assumes the two
210+generated functions `getPoint` and `getBooks` in scope. Therefore we need to
211+write the generated javascript into a file:
176``` haskell
213``` haskell
177writeJSFiles :: IO ()
214writeJSFiles :: IO ()
178writeJSFiles = do
215writeJSFiles = do
179− T.writeFile "getting-started/gs9/api.js" apiJS
216+ T.writeFile "static/api.js" apiJS
180 jq <- T.readFile =<< Language.Javascript.JQuery.file
217 jq <- T.readFile =<< Language.Javascript.JQuery.file
181− T.writeFile "getting-started/gs9/jq.js" jq
218+ T.writeFile "static/jq.js" jq
184−And we're good to go. Start the server with `dist/build/tutorial/tutorial 9` and go to `http://localhost:8081/`. Start typing in the name of one of the authors in our database or part of a book title, and check out how long it takes to approximate π using the method mentioned above.
221+(We're also writing the jquery library into a file, as it's also used by
222+`ui.js`.) `static/api.js` will be included in `index.html` and the two
223+generated functions will therefore be available in `ui.js`.
225+And we're good to go. You can start the `main` function of this file and go to
226+`http://localhost:8000/`. Start typing in the name of one of the authors in our
227+database or part of a book title, and check out how long it takes to
228+approximate pi using the method mentioned above.