API with NestJS #185. Operations with PostGIS Polygons in PostgreSQL and Drizzle
When using PostgreSQL with PostGIS, we can do various operations using polygons. In this article, we learn how to do that both through raw SQL queries and the Drizzle ORM. Storing polygons using the Drizzle ORM To store polygons using the Drizzle ORM, we use a custom data type and the areas table. database-schema.ts
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 |
import { serial, text, pgTable } from 'drizzle-orm/pg-core'; import { customType } from 'drizzle-orm/pg-core'; import { Geometry } from 'wkx'; type Coordinate = [number, number]; interface GeoJson { type: string; coordinates: Coordinate[][]; } const polygon = customType<{ data: Coordinate[][]; driverData: string }>({ dataType() { return 'geometry(Polygon, 4326)'; }, toDriver(coordinates: Coordinate[][]): string { return JSON.stringify({ type: 'Polygon', coordinates, }); }, fromDriver(data: string) { const geoJson = Geometry.parse( Buffer.from(data, 'hex'), ).toGeoJSON() as GeoJson; return geoJson.coordinates; }, }); export const areas = pgTable('areas', { id: serial().primaryKey(), name: text().notNull(), polygon: polygon('polygon').notNull(), }); export const databaseSchema = { areas, }; |
[…]