@@ -1,9 +1,7 @@
11# Generating Javascript functions to query an API
22
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
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*.
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.
75
86For this, we will consider a simple page divided in two parts. At the top, we
97will have a search box that lets us search in a list of Haskell books by
@@ -32,10 +30,11 @@ import Data.Aeson
3230import Data.Proxy
3331import Data.Text as T (Text)
3432import Data.Text.IO as T (writeFile, readFile)
35−import qualified Data.Text as T
3633import GHC.Generics
3734import Language.Javascript.JQuery
3835import Network.Wai
36+import Network.Wai.Handler.Warp
37+import qualified Data.Text as T
3938import Servant
4039import Servant.JS
4140import System.Random
@@ -78,7 +77,8 @@ book :: Text -> Text -> Int -> Book
7877book = Book
7978```
8079
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.
8282
8383``` haskell
8484books :: [Book]
@@ -92,7 +92,10 @@ books =
9292 ]
9393```
9494
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.
9699
97100``` haskell
98101searchBook :: Monad m => Maybe Text -> m (Search Book)
@@ -106,7 +109,9 @@ searchBook (Just q) = return (mkSearch q books')
106109 q' = T.toLower q
107110```
108111
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`.
110115
111116``` haskell
112117randomPoint :: MonadIO m => m Point
@@ -131,54 +136,93 @@ server = randomPoint
131136
132137server' :: Server API'
133138server' = server
134− :<|> serveDirectory "tutorial/t9"
139+ :<|> serveDirectory "static"
135140
136141app :: Application
137142app = serve api' server'
143+
144+main :: IO ()
145+main = run 8000 app
138146```
139147
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.
148+Why two different API types, proxies and servers though? Simply because we
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.
141151
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
154+`Servant.JQuery`.
143155
144156``` haskell
145157apiJS :: Text
146158apiJS = jsForAPI api vanillaJS
147159```
148160
149−This `String` contains 2 Javascript functions:
161+This `Text` contains 2 Javascript functions, 'getPoint' and 'getBooks':
150162
151163``` javascript
152−
153−function getpoint(onSuccess, onError)
164+var getPoint = function(onSuccess, onError)
154165{
155− $.ajax(
156− { url: '/point'
157− , success: onSuccess
158− , error: onError
159− , method: 'GET'
160− });
166+ var xhr = new XMLHttpRequest();
167+ xhr.open('GET', '/point', true);
168+ xhr.setRequestHeader("Accept","application/json");
169+ xhr.onreadystatechange = function (e) {
170+ if (xhr.readyState == 4) {
171+ if (xhr.status == 204 || xhr.status == 205) {
172+ onSuccess();
173+ } else if (xhr.status >= 200 && xhr.status < 300) {
174+ var value = JSON.parse(xhr.responseText);
175+ onSuccess(value);
176+ } else {
177+ var value = JSON.parse(xhr.responseText);
178+ onError(value);
179+ }
180+ }
181+ }
182+ xhr.send(null);
161183}
162184
163−function getbooks(q, onSuccess, onError)
185+var getBooks = function(q, onSuccess, onError)
164186{
165− $.ajax(
166− { url: '/books' + '?q=' + encodeURIComponent(q)
167− , success: onSuccess
168− , error: onError
169− , method: 'GET'
170− });
187+ var xhr = new XMLHttpRequest();
188+ xhr.open('GET', '/books' + '?q=' + encodeURIComponent(q), true);
189+ xhr.setRequestHeader("Accept","application/json");
190+ xhr.onreadystatechange = function (e) {
191+ if (xhr.readyState == 4) {
192+ if (xhr.status == 204 || xhr.status == 205) {
193+ onSuccess();
194+ } else if (xhr.status >= 200 && xhr.status < 300) {
195+ var value = JSON.parse(xhr.responseText);
196+ onSuccess(value);
197+ } else {
198+ var value = JSON.parse(xhr.responseText);
199+ onError(value);
200+ }
201+ }
202+ }
203+ xhr.send(null);
171204}
172205```
173206
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:
175212
176213``` haskell
177214writeJSFiles :: IO ()
178215writeJSFiles = do
179− T.writeFile "getting-started/gs9/api.js" apiJS
216+ T.writeFile "static/api.js" apiJS
180217 jq <- T.readFile =<< Language.Javascript.JQuery.file
181− T.writeFile "getting-started/gs9/jq.js" jq
218+ T.writeFile "static/jq.js" jq
182219```
183220
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`.
224+
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.