-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
83 lines (66 loc) · 1.55 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var sublevel = require('level-sublevel'),
es = require('event-stream'),
geoUtils = require('./lib/geo-utils'),
rTree = require('rtree');
module.exports = function (_db) {
function Geo() {}
_db = sublevel(_db);
Geo.prototype = _db.sublevel('data');
var _index = _db.sublevel('index'),
db = new Geo(),
rtree = rTree();
//
// Expose rTree index
//
db._rtree = rtree;
//
// Load Index
//
_index.get('_index', function (err, val) {
if (!err) {
rtree.setTree(val);
}
});
//
// Override put
//
var put = db.put;
db.put = function (key, val, cb) {
if (geoUtils.isGeo(val)) {
geoUtils.getGeoJSON(key, val, function (json) {
rtree.geoJSON(json);
_saveIndex();
});
}
put.call(db, key, val, { valueEncoding: 'json'}, cb);
};
//
// Override get
//
var get = db.get;
db.get = function (key, cb) {
get.call(db, key, { valueEncoding: 'json' }, cb);
};
//
// Search Stream
//
db.createSearchStream = function (opts) {
var results = rtree.bbox(opts.bbox || []);
var ts = es.map(function (data, callback) {
var self = this;
var key = data.properties['_key'];
db.get(key, function (err, value) {
if (err) return callback(err);
callback(null, { key: key, value: value });
});
});
return es.readArray(results).pipe(ts);
};
//
// Save index structure in db
//
function _saveIndex() {
_index.put('_index', rtree.getTree(), function (err) {});
}
return db;
};