Objection.js: Automatic createdAt & updatedAt

Created on 13 Nov 2015  路  5Comments  路  Source: Vincit/objection.js

For each table I have createdAt and updatedAt and it s redondant to set it in each beforeCreate/Update It is possible to add a static option to add it automatically ex:

class Foo extends Model {

    static $createdAt = 'tableName'
    static $UpdatedAt = 'tableName'

}

Most helpful comment

Basic OOP saves you here. Just create a base class:

class ModelBase  extends Model {
  $beforeUpdate() {
    this.updatedAt = new Date().toISOString();
  }

  $beforeInsert() {
    this.createdAt = new Date().toISOString();
  }
}

and then inherit all your models from ModelBase instead of Model. This way the code is only in once place.

All 5 comments

Basic OOP saves you here. Just create a base class:

class ModelBase  extends Model {
  $beforeUpdate() {
    this.updatedAt = new Date().toISOString();
  }

  $beforeInsert() {
    this.createdAt = new Date().toISOString();
  }
}

and then inherit all your models from ModelBase instead of Model. This way the code is only in once place.

but I need to call super in this case

So you have $beforeUpdate and $beforeInsert implemented for all your models to do different things in addition to settings the timestamps? If they do common stuff, just move them to the parent class. If they do different things and you cannot move the implementation to the parent class then yes, you need to call super.

You do know that you don't need to implement the $before methods if they do nothing but call super() right? :)

I always add those timestamps in the database using triggers. Have you considered that?

Yeah I know for super, but I have to set a random pid in beforeInsert for example but I go look for triggers

Basic OOP saves you here. Just create a base class:

class ModelBase  extends Model {
  $beforeUpdate() {
    this.updatedAt = new Date().toISOString();
  }

  $beforeInsert() {
    this.createdAt = new Date().toISOString();
  }
}

and then inherit all your models from ModelBase instead of Model. This way the code is only in once place.

I think its best to remove the createdAt field when updating

   $beforeUpdate() {
     delete this.createdAt;
     this.updatedAt = new Date().toISOString();
   }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

louis-etne picture louis-etne  路  4Comments

nicolaracco picture nicolaracco  路  3Comments

purepear picture purepear  路  3Comments

rickmed picture rickmed  路  4Comments

ghost picture ghost  路  3Comments