Lack of documentation on serialization of custom Javascript
UsamaButt1593 opened this issue · comments
Parsing Postgres types is well documented on node-pg-types like to parse every TIMESTAMPZ
type into a Moment
object, we can do something like:
var types = require('pg').types
var moment = require('moment')
var parseFn = function(val) {
return val === null ? null : moment(val)
}
types.setTypeParser(types.builtins.TIMESTAMPTZ, parseFn)
But there is complete lack when it comes behaviour of library while serializing Javascript objects used as values
inside pool.query
or client.query
method.
For example, if i pass a Moment
object, how is it serialized? Is it done by calling Moment#toString()
method? What if a library user wants to describe custom srialization behaviour? As I want to use Moment#toISOString()
whenever a Moment
object is passed to query.
Lets consider an example:
CREATE TABLE IF NOT EXISTS RefreshToken (
id SERIAL PRIMARY KEY NOT NULL,
token TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
import moment from 'moment';
const token = "xxxxx.yyyyy.zzzzz";
const expires_at = moment().add(1, 'days'); // local time zone
const result = await pool.query({
text: 'INSERT INTO RefreshToken(token, expires_at) VALUES ($1, $2)',
values: [
token,
expires_at.toISOString() // I want ISO-8601 UTC timestamp to be passed to Postgres. But it is so easy to forget to call toISOString on every query.
],
});
Is there any thing like require('pg').types.setTypeSerializer(Moment /* Javascript Type*/, serializeFn)
???
Thanks much. I realize that it is indeed mentioned in the docs.