Search code examples
node.jstypescriptgeometrypostgistypeorm

How to handle geometry field in PostGIS with TypeORM


I am using TypeORM which is connected to a local postgis instance running from this image

This is my entity file (Geometry comes from this package):

@Entity()
export class Port {
  @Column({ type: 'geometry' })
  geometry: Geometry;
}

Here I can see that TypeORM succeeded in creating the database.

(screenshot from pgadmin)

However when I try to insert any port, TypeORM throws:

QueryFailedError: unknown GeoJSON type

Data I am trying to insert is in WKT format. For example

"POINT(18.5478833 54.5353333)"

What am I doing wrong?


Solution

  • Ok so what I ended up using is:

    Entity

    @Column({
      type: 'geometry',
      srid: 4326,
    })
    geometry: string;
    

    Service

    public async create(version: CreateTDTO): Promise<T> {
      return this.baseZoneVersionRpository
        .createQueryBuilder()
        .insert()
        .values({
          ...(version as any),
          geometry: () => `ST_GeomFromText('${version.geometry}', 4326)`,
        })
        .execute() as any;
    }
    

    Note that this one expects input data in a WKT format.

    Unfortunately I didn't find a way to get rid of any

    Change format coming from database

    I am not sure why but my PostGIS database returns data in GeoJSON format by default and I haven't been able to change it through the TypeORM. There is a way however to transform entities using TypeORM's transformer.

    @Column({
      type: 'geometry',
      srid: 4326,
      transformer: {
        to: (something) => something,
        from: transformFromGeoJSONToYourFormat,
      },
    })
    geometry: string;
    

    Library I found particularly helpfull for changing geometry formats was https://www.npmjs.com/package/wkx