How do I write this in Bookshelfjs and knex

501 views Asked by At

I'm making a simple session store from bookshelfjs, but I need to set the timestamp column correctly. I'm trying to write the column's ttl with now() + ttl interval of 1ms, but I can't recall how to get it done, or how to trigger raw content for that column:

var Session = Models.Bookshelf.Model.extend({
  tableName: 'sessions',
  idAttribute: 'id'
},{
  get: Promise.method(function(sid){
    console.log("Fetching SID = ", sid);
    return new this({id: sid}).fetch();
  }),
  set: Promise.method(function(sid, session, ttl){
    console.log("Setting SID = ", sid);
    console.log("Setting SID session = ", session );
    console.log("Setting SID ttl = ", ttl);
    new this({id: sid}).save({session: session, expiry: "(now() + " + ttl + " * interval '1 ms')" });
  }),
  destroy: Promise.method(function(sid){
    this.destroy({id: sid});
  })
});

The original Query from koa-pg-session is:

UPDATE %I.%I SET session = $1, expiry = (now() + $2 * interval '1 ms') WHERE id = $3;

I'm sure it's with Knex's raw query formatter, but I can't find the correct part in the documentation for setting a the column's value. I don't want to write the full query in a string, I want to know how to do it for just the single column 'expiry'.

1

There are 1 answers

1
uglycode On BEST ANSWER

I haven't tested this, tell me if it works (you need to require knex first, of course):

new this({id: sid}).save({session: session, expiry: knex.raw("(now() + " + ttl + " * interval '1 ms')") });