Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helpful utility for converting postgis data into GeoJSON as it comes out of the db, and vice versa.
var wkx = require('wkx')
var pg = require('pg')
var pgUtil = require('pg/lib/utils')
const geoParser = {
init(knex){
// 1. Convert postgis data coming out of the db into geoJSON
// Every postgres installation will have different oids for postgis geo types.
knex
.raw('SELECT oid, typname AS name FROM pg_type WHERE typname IN (\'geography\', \'geometry\');')
.then(({rows}) => {
if (!rows || !rows.length){
// TODO: this is currently fatal - should it be graceful?
throw new Error('postgis not installed')
}
rows.forEach(({oid, name}) =>
pg.types.setTypeParser(oid, (val) => geoParser.postgisToGeoJSON(val))
)
})
// 2. Convert geoJSON data going into the database into postgis
// node-postgres recommends overwriting this function for custom handling
const oldPrepare = pgUtil.prepareValue
pgUtil.prepareValue = function(val){
if (val && typeof val === 'object' && val.type && val.coordinates){
// quacks like a geoJSON object
const value = geoParser.geoJSONToPostgis(val)
return value
}
return oldPrepare.call(pgUtil, val)
}
},
postgisToGeoJSON(val){
const wkbBuffer = new Buffer(val, 'hex')
const geometry = wkx.Geometry.parse(wkbBuffer)
return geometry.toGeoJSON()
},
geoJSONToPostgis(val){
if (typeof val === 'object'){
const parsed = wkx.Geometry.parseGeoJSON(val)
return parsed.toEwkt()
}
return val
}
}
module.exports = geoParser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment