-
Notifications
You must be signed in to change notification settings - Fork 5
/
freeCat.js
68 lines (58 loc) · 1.49 KB
/
freeCat.js
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
var util = require('util')
, qs = require('querystring')
// Dependencies
, request = require('request')
, es = require('event-stream')
, clarinet = require('clarinet')
// vars
, freeCat
;
freeCat = function (topics, cb) {
if (typeof topics === 'string') topics = [ topics ]
var lookup
, results = []
;
lookup = function (item) {
var q =
{ query: JSON.stringify({ query:
{ name: item
, type: [{ name: null }]
}
})}
, parse = clarinet.createStream()
, topic = false
, isTopic = function (name) {
if (name === 'name') topic = true
}
parse.write = function (data) {
this._parser.write(data.toString())
return true
}
parse.on('openobject', isTopic)
parse.on('key', isTopic)
parse.on('value', function (value) {
if (topic) {
parse.emit('data', value)
topic = false
}
})
return request(
'http://www.freebase.com/api/service/mqlread?' + qs.stringify(q)
).pipe(parse)
}
results = topics.map(lookup)
if (typeof cb === 'function') {
es.concat.apply(null, results)
.pipe(es.writeArray(cb))
} else {
return es.concat.apply(null, results)
}
}
module.exports = exports = freeCat
// Example usage
// freeCat(['Jon Snow', 'Arya Stark', 'Ghost'], function (e, results) {
// if (e) throw e
// console.log(results.reverse())
// })
//
// freeCat(['Doc Watson', 'Earl Scrugs', 'Woody Guthrie']).pipe(es.log())