Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lack of documentation on serialization of custom Javascript #3200

Closed
UsamaButt1593 opened this issue Apr 25, 2024 · 2 comments
Closed

Lack of documentation on serialization of custom Javascript #3200

UsamaButt1593 opened this issue Apr 25, 2024 · 2 comments

Comments

@UsamaButt1593
Copy link

UsamaButt1593 commented Apr 25, 2024

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)???

@boromisp
Copy link
Contributor

boromisp commented Apr 25, 2024

@UsamaButt1593
Copy link
Author

https://node-postgres.com/features/queries

Thanks much. I realize that it is indeed mentioned in the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants