user3871
user3871

Reputation: 12718

bookshelf/knex add time to timestamp

Using NodeJS, Knex, Bookshelf JS ORM, and PostgreSQL, I have a field table.timestamp('reset_password_expires'); - how can I set the date for future (let's say 10 minutes from now)?

I've tried:

new User.User({'email': email}).fetch().then((user) => {
      user.set('reset_password_expires', Date.now() + 60000);
      user.save();
      ...

But this throws:

Unhandled rejection error: date/time field value out of range: "1544577763253"

Also tried

user.set('reset_password_expires', 'NOW()' + '10 minutes'::interval);

But this is invalid syntax.

I've also tried changing field type to dateTime, with the same results.

Upvotes: 0

Views: 1812

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18969

I think PostgreSQL requires timestamp to be on ordinary datetime format (as described here). At the moment you are passing milliseconds since epoch.

In Developer Tools:

> Date.now() + 60000
1544706877041

You can try using this instead:

new Date((new Date()).getTime() + 60000)

In Developer Tools:

> new Date((new Date()).getTime() + 60000)
Thu Dec 13 2018 14:15:50 GMT+0100 (Central European Standard Time)

Here is a utility function that I use myself:

module.exports.inHours = (hours) => {
  const minutes = hours * 60;
  const seconds = minutes * 60;
  const milliseconds = seconds * 1000;

  return new Date((new Date()).getTime() + milliseconds);
};

My code looks slightly different than yours, but this is how I call the function:

await userQueries.update(user.user_id, {
  resetPasswordToken: resetToken,
  resetPasswordExpires: inHours(1),
  modified_at: new Date(),
});

This is a datetime, however, not a timestamp.

Upvotes: 1

Related Questions