forked from tyke/node-mixpanel-data-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (81 loc) · 2.6 KB
/
index.js
File metadata and controls
86 lines (81 loc) · 2.6 KB
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
84
85
86
var crypto = require('crypto')
, url = require('url')
, _ = require('underscore')
, mixpanel_methods = [
'events'
, 'events/top'
, 'events/names'
, 'events/properties'
, 'events/properties/top'
, 'events/properties/values'
, 'funnels'
, 'funnels/list'
, 'segmentation'
, 'segmentation/numeric'
, 'segmentation/sum'
, 'segmentation/average'
, 'retention'
, 'engage'
]
var mixpanel_exporter = function(args) {
_.extend(this, {
parsed_url: url.parse('http://mixpanel.com/api/2.0/', true)
, format: 'json'
, methods: mixpanel_methods
, request: require('request')
}, args)
if(!this.api_key) throw new Error('Missing Mixpanel API Key')
if(!this.api_secret) throw new Error('Missing Mixpanel API Secret')
}
mixpanel_exporter.prototype.alphabetical_sort = function(obj) {
return _.reduce(_.keys(obj).sort(), function(sorted, el) {
sorted[el] = obj[el]
return sorted
}, {})
}
mixpanel_exporter.prototype.hash = function(string) {
return crypto.createHash('md5').update(string).digest('hex')
}
mixpanel_exporter.prototype.get_signature = function(obj) {
return this.hash(_.reduce(obj, function(sig, val, key) {
sig += key + '=' + (obj[key])
return sig
}, '') + this.api_secret)
}
mixpanel_exporter.prototype.stringify_array = function(obj) {
return _.reduce(obj, function(stringified, val, key) {
if(_.isArray(val)) {
val = JSON.stringify(val)
}
stringified[key] = val
return stringified
}, {})
}
mixpanel_exporter.prototype.generate_args = function(endpoint, _args) {
var args = this.stringify_array(_.extend({
api_key: this.api_key
, expire: Date.now() + 1000
, format: this.format
}, _args))
var sorted_args = this.alphabetical_sort(args)
, signature = this.get_signature(sorted_args)
, parsed_url = _.clone(this.parsed_url)
return url.format(_.extend(parsed_url, {
pathname: parsed_url.path += endpoint
, query: _.extend({}, sorted_args, {
sig: signature
})
}))
}
mixpanel_exporter.prototype.fetch = function(endpoint, args, callback) {
this.request(this.generate_args(endpoint, args), function(error, response, body) {
if(error) return callback(error)
callback(null, response, body)
})
}
_.each(mixpanel_methods, function(method) {
mixpanel_exporter.prototype[method.replace('/', '_')] = function(args, callback) {
this.fetch(method, args, callback)
}
})
module.exports = mixpanel_exporter