Skip to content

Instantly share code, notes, and snippets.

@robshep
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save robshep/863576684e137dfca9de to your computer and use it in GitHub Desktop.

Select an option

Save robshep/863576684e137dfca9de to your computer and use it in GitHub Desktop.
basic restify/node.js based server for providing GeoJSON features
// npm install restify pg
/**
* Configure the tables and the columns required as properties
*/
var tables = {
'boundary' : { geom:'polygon', cols:['id', 'area_id', 'org_id'] },
'stage' : { geom:'route', cols:['id', 'event_id', 'name', 'outandback', 'start_time', 'num', 'distance'] },
'stagepoi' : { geom:'point', cols:['id', 'stage_id', 'type' ] }
};
var connString = 'tcp://username:password@host:port/dbname';
////////////////////////////////////////
var restify = require('restify');
var pg = require("pg");
function byProp(req, res, next){
var vals = []
var clause = "WHERE " + req.params.prop + " = $1"
vals.push(req.params.id)
execute(req,res,next,clause,vals)
}
function execute(req, res, next, clause, vals) {
var table = req.params.table;
// check table exists
var cfg = tables[table];
var cols2props = cfg.cols.join(",")
var geom = cfg.geom
pg.connect(connString, function(err, client) {
// from http://www.postgresonline.com/journal/archives/267-Creating-GeoJSON-Feature-Collections-with-JSON-and-PostGIS-functions.html
var sql = "SELECT row_to_json(fc) " +
"FROM ( SELECT 'FeatureCollection' As type, " +
"row_to_json( (SELECT l FROM (SELECT 'name' as type, row_to_json( (SELECT l2 FROM (SELECT 'urn:ogc:def:crs:EPSG::'||Find_SRID('public', '@TABLE@', '@GEOM@') as name) as l2) ) as properties ) As l) ) as crs, " +
"array_to_json(array_agg(f)) As features " +
"FROM (SELECT 'Feature' As type " +
", ST_AsGeoJSON(lg.@GEOM@, 0)::json As geometry " +
", row_to_json((SELECT l FROM ( SELECT @PROPS@ ) As l " +
")) As properties " +
"FROM @TABLE@ As lg @CLAUSE@ ) As f ) As fc;";
var query = sql.replace(/@TABLE@/g, table)
.replace(/@GEOM@/g, geom)
.replace(/@PROPS@/g, cols2props)
.replace(/@CLAUSE@/g, !!(clause) ? clause : "" );
console.log(query)
client.query(query, vals, function(err, result) {
res.send(result.rows[0].row_to_json);
client.end()
next();
});
});
}
var server = restify.createServer();
server.use(restify.CORS());
server.get('/:table', execute);
server.get('/:table/:prop/:id', byProp);
server.listen(8088, function() {
console.log('%s listening at %s', server.name, server.url);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment