-
Notifications
You must be signed in to change notification settings - Fork 0
/
psql-provider.js
64 lines (51 loc) · 1.48 KB
/
psql-provider.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
'use strict';
const pg = require('pg');
const SphericalMercator = require('@mapbox/sphericalmercator');
const hstore = require('pg-hstore')();
/**
**
** @param {options.buffer} buffer around the tile in pixels. Default 0
** @param {options.generateSQL}:function
**
**/
function PsqlProvider(options={}) {
this.options = Object.assign({
buffer: 0
}, options);
if (typeof(options.generateSQL) !== 'function') {
throw new Error("options.generateSQL must be a function");
}
this.pool = new pg.Pool(options.pgConfig);
this.pool.on('error', (err, client) => {
console.error('Unexpected error on idle client', err)
process.exit(-1)
});
}
function transformData(result, bbox) {
const data = {
"type": "FeatureCollection",
"bbox": bbox
};
data.features = result.rows.map((row) => {
if (!row.geojson) {
return null;
}
return {
"type": "Feature",
"geometry": JSON.parse(row.geojson),
"properties": hstore.parse(row.tags)
};
}).filter((x) => !!x);
return data;
}
PsqlProvider.prototype.getTileData = function(bbox, z) {
let bboxSQL = 'ST_SetSRID(\'BOX(' + bbox[0] + ' ' + bbox[1] + ',' + bbox[2] + ' ' + bbox[3] + ' )\'::box2d, 3857)';
if (this.options.buffer > 0) {
bboxSQL = "ST_Expand(" + bboxSQL + ", " + this.options.buffer + ")";
}
const sql = this.options.generateSQL(bboxSQL, z);
return this.pool.query(sql).then(result => {
return transformData(result, bbox);
});
}
module.exports = PsqlProvider;