Vincit / objection.js

An SQL-friendly ORM for Node.js
https://vincit.github.io/objection.js
MIT License
7.24k stars 635 forks source link

How would you implement logging with objection? #69

Closed tnrich closed 8 years ago

tnrich commented 8 years ago

Hey there,

I was wondering how you'd go about implementing "activity logging" using objectionjs. Bookshelf, for example, gives some nice hooks on its model objects like "onCreated", "onSaved", etc. which greatly aid in the logging of user activity.

Does objectionjs have something similar, and if not, how would you go about determining if, say, a user created a new record and logging that action?

Thanks!

koskimas commented 8 years ago

Hi,

You can override the $afterInsert and $afterUpdate methods of a model:

class Person extends Model {
  $afterInsert() {
    console.log(`person ${this.name} created`);
  }
  $afterUpdate() {
    console.log(`person ${this.name} updated: ${JSON.stringify(this)}`);
  }
}

It's a good practice to create a some BaseModel class from which all your models inherit so that you can put common stuff in it. For example logging any created record could be achieved like this:

class BaseModel extends Model {
  $afterInsert() {
    console.log(`${this.constructor.name} instance created`);
  }
  $afterUpdate() {
    console.log(`${this.constructor.name} instance updated: ${JSON.stringify(this)}`);
  }
}

class Person extends BaseModel {
  ...
}

class Animal extends BaseModel {
  ...
}
tnrich commented 8 years ago

Hmm thanks for the info!