Created
November 9, 2018 00:47
-
-
Save DesignByOnyx/1f602e82021d277f47e7a07362bb2d34 to your computer and use it in GitHub Desktop.
Helpful utility for converting postgis data into GeoJSON as it comes out of the db, and vice versa.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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