Created
October 21, 2023 15:23
-
-
Save ItsWendell/65a107c0f8de00fdd6e4f3935789ce5a to your computer and use it in GitHub Desktop.
Experimental / hacky custom drizzle column for PostGIS geometry (injection method)
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
export type GeometryTypes = { | |
Point: GeoJSON.Point; | |
LineString: GeoJSON.LineString; | |
Polygon: GeoJSON.Polygon; | |
MultiPoint: GeoJSON.MultiPoint; | |
MultiLineString: GeoJSON.MultiLineString; | |
MultiPolygon: GeoJSON.MultiPolygon; | |
GeometryCollection: GeoJSON.GeometryCollection; | |
}; | |
/** | |
* Experimental custom type for PostGIS geometry, only supports Point and LineString. | |
*/ | |
export const geometryType = < | |
TType extends GeoJSON.Geometry["type"] = GeoJSON.Geometry["type"], | |
T extends CustomTypeValues = CustomTypeValues, | |
>( | |
dbName: string, | |
fieldConfig?: T["config"] & { type: TType }, | |
) => { | |
const type = fieldConfig?.type; | |
return customType<{ | |
data: GeometryTypes[TType]; | |
}>({ | |
dataType() { | |
return type ? `geometry(${type},4326)` : "geometry"; | |
}, | |
toDriver(value) { | |
throw new Error("Not implemented"); | |
}, | |
fromDriver(value) { | |
try { | |
const data = JSON.parse(value as string); | |
if (type && data.type !== type) { | |
throw new Error(`Expected geometry type ${type}, got ${data.type}`); | |
} | |
return data as GeometryTypes[TType]; | |
} catch (e) { | |
throw new Error(`Failed to parse geometry`, { | |
cause: e, | |
}); | |
} | |
}, | |
})(`public".ST_AsGeoJSON("${dbName}") as "${dbName}`, { | |
...fieldConfig, | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@madebyfabian @hauserkristof @fvaldes33 I've also written an alternative implementation by parsing the actual values from the database:
https://gist.github.com/ItsWendell/38ebe96b34d00d9138ce23cc363d7009