-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrowsy_persistence.coffee
83 lines (68 loc) · 2.34 KB
/
drowsy_persistence.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
http = require('http')
httpRequest = require('request')
events = require('events')
class DrowsyPersistence extends events.EventEmitter
constructor: (@config) ->
added: ->
console.log "Drowsy persistence enabled. Broadcasts will be saved to #{@drowsyUrl()} ..."
incoming: (message, callback) ->
#return callback(message)
if message.channel.match /^\/meta\//
return callback(message) # ignore this message
cb2 = (message) ->
console.log("Calling callback!")
callback(message)
this.persistInDrowsy message, cb2
actionMethodMap =
create: 'POST'
update: 'PUT'
patch: 'PATCH'
delete: 'DELETE'
persistInDrowsy: (message, callback) ->
cid = message.clientId
channel = message.channel
payload = message.data
if @config.uri?
baseUri = @config.uri.replace(/\/$/,'')
else
scheme = @config.scheme ? 'http'
hostname = @config.hostname ? 'localhost'
port = @config.port ? 9292
baseUri = "#{scheme}://#{hostname}:#{port}"
path = channel
# if @config.username? and @config.password?
# authHash =
# user: @config.username
# pass: @config.password
if @config.username? and @config.password?
reqOpts =
uri: "#{baseUri}/#{path}"
method: actionMethodMap[payload.action]
json: payload.data
auth:
user: @config.username
pass: @config.password
else
reqOpts =
uri: "#{baseUri}/#{path}"
method: actionMethodMap[payload.action]
json: payload.data
httpRequest reqOpts, (err, res, json) =>
if err
@emit 'persist_failure', cid, channel, payload, err
errMsg = "\n\n!!! Error while sending request to Drowsy!
Is the Drowsy server up and running at #{this.drowsyUrl()}?\n
#{err.toString()}"
console.error errMsg
message.error = errMsg
callback(message)
throw err
if res.statusCode in [200...299]
@emit 'persist_success', cid, channel, payload, res, json
else
@emit 'persist_failure', cid, channel, payload, res, json
message.error = "Failed to persist data in Drowsy; Drowsy responded with a #{res.statusCode}"
callback(message)
drowsyUrl: ->
"#{@config.scheme}://#{@config.hostname}:#{@config.port}"
exports.DrowsyPersistence = DrowsyPersistence