/
service.coffee
50 lines (37 loc) · 1.04 KB
/
service.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
###
# Web Service for lipsum.com
Provides the low-level interface to the lipsum.com
service.
###
http = require 'http'
url = require 'url'
class Service
get: (format, callback, queryOpts) ->
###
Retrieves the lipsum text.
format: {String} one of "xml" or "json"
callback: {Function} called on successful text retrieval.
Should have one parameter to hold the response data.
queryOpts: {Object} options to attach to the query portion of the url.
###
urlopts =
protocol: 'http:'
hostname: 'lipsum.com'
pathname: "/feed/#{format}"
if queryOpts?
urlopts.query = queryOpts
endpoint = url.format urlopts
req = http.request(endpoint, (res) ->
payload = ""
res.setEncoding('utf8')
res.on('data', (chunk) ->
payload += chunk.replace(/[\n|\t|\f|\v|\r]+/g, "\\n")
)
res.on('end', ->
callback(payload)
)
).on('error', (err) ->
throw new Error("Service Error: #{err.message}")
)
req.end()
module?.exports = Service