Client.icl 1.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
implementation module Cloogle.Client

from StdFunc import flip, o

from Control.Monad import class Monad(bind), =<<
import Data.Error
from Data.Func import $
import Data.Functor
import Data.Map
import Data.Tuple
import Internet.HTTP
from Text import class Text(join), instance Text String, instance + String
import Text.Encodings.UrlEncoding
import Text.GenJSON

import Cloogle.API

Camil Staps's avatar
Camil Staps committed
18
toHTTPRequest :: !Request -> HTTPRequest
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
toHTTPRequest req =
	{ newHTTPRequest
	& req_method   = HTTP_GET
	, req_path     = "/api.php"
	, req_query    = "?" + urlEncodePairs params
	, req_headers  = put "User-Agent" "Clean/libcloogle" newMap
	, server_name  = "cloogle.org"
	}
where
	params = catMaybes
		[ tuple "str"                          <$> toSingleLine req
		, tuple "lib"              o join ","  <$> req.libraries
		, tuple "mod"              o join ","  <$> req.modules
		, tuple "include_builtins" o printBool <$> req.include_builtins
		, tuple "include_core"     o printBool <$> req.include_core
		, tuple "page"             o toString  <$> req.page
		]
	where printBool b = if b "true" "false"

Camil Staps's avatar
Camil Staps committed
38
request :: !Request !*World -> *(MaybeErrorString Response, *World)
39 40 41 42 43 44
request req w = appFst ((=<<) parseResponse) $ doHTTPRequest (toHTTPRequest req) 10000 w
where
	parseResponse :: HTTPResponse -> MaybeErrorString Response
	parseResponse res = case fromJSON $ fromString res.rsp_data of
		Nothing -> Error "Invalid JSON"
		Just r  -> Ok r