brianc / node-pg-types

Type parsing for node-postgres
267 stars 54 forks source link

should handle null values #135

Closed chan-nguyen closed 2 years ago

chan-nguyen commented 2 years ago

Currently, the lib states that null values are never parsed.. However, in some use-cases, we may need to convert null to undefined or some defined value.

Is it possible to handle returned null values ?

Code example:

var types = require('pg').types

types.setTypeParser(20, (val) => val ? parseInt(val) : 0) // BigInt or BigSerial
types.setTypeParser(1043, (val) => val ?? '') // varchar
types.setTypeParser(214310, (val) => val ?? undefined) // user defined type
bendrucker commented 2 years ago

This package does not handle nulls, but it's actually pg that ensures that nulls are never parsed:

https://github.com/brianc/node-postgres/blob/4b229275cfe41ca17b7d69bd39f91ada0068a5d0/packages/pg/lib/result.js#L67-L69

So no, you cannot customize parsing of nulls here (or in pg). Changing that is either breaking or requires a whole separate API for handling nulls for each type. I don't expect we'd implement either.

This package's job is to convert returned PG values into the best equivalent JavaScript type. Any additional processing can be performed on the resultant objects.

If you want to have zero values rather than null, that can be accomplished at the database level via column defaults.

Happy to hear more about the use case though.