MokoJs / moko

Generator powered models
51 stars 3 forks source link

Transform toJSON output #7

Closed paglias closed 10 years ago

paglias commented 10 years ago

I would like not to expose some database fields publicly and would love the ability to specify an optional transform function to be executed after the normal toJSON output is created.

If you don't want to add this to the core library then calling require('moko')(modelName) could return a child class with a reference to the super class allowing for custom methods to extend the original ones.

rschmukler commented 10 years ago

You can just do:


var User = moko('User')

User.prototype.someJsonFormat = function() {
  var json = this.toJSON();
  delete json.encyptedPassword
  delete json.somethingElse
  return json
};

Does this work for you?

Also, you might find paramd helpful.

paglias commented 10 years ago

@rschmukler that code causes a maximum call stack size exceeded error because it ends up calling itself

rschmukler commented 10 years ago

Are you sure? This code sample works for me...

var moko = require('moko'),
    co   = require('co');

var User = moko('User');

User.attr('name').attr('password');

User.prototype.someJSON = function() {
  var json = this.toJSON();
  delete json.password;
  return json;
};

co(function*() {
  var user = yield new User({name: 'Bob', password: '12345' });
  console.log(user.someJSON());
})();
paglias commented 10 years ago

oh yes that works I meant overriding the toJSON directly because it's used by Koa when printing json responses

2014-06-09 21:26 GMT+02:00, Ryan Schmukler notifications@github.com:

Are you sure? This code sample works for me...

var moko = require('./'),
    co   = require('co');

var User = moko('User');

User.attr('name').attr('password');

User.prototype.someJSON = function() {
  var json = this.toJSON();
  delete json.password;
  return json;
};

co(function*() {
  var user = yield new User({name: 'Bob', password: '12345' });
  console.log(user.someJSON());
})();

Reply to this email directly or view it on GitHub: https://github.com/MokoJs/moko/issues/7#issuecomment-45532904

Matteo Pagliazzi - paglias.net

rschmukler commented 10 years ago

Ah. Alright, I think this will do what you want then:

var moko = require('./'),
    co   = require('co');

var User = moko('User');

User.attr('name').attr('password');

var toJSON = User.prototype.toJSON;
User.prototype.toJSON = function() {
  var json = toJSON.call(this);
  delete json.password;
  return json;
};

co(function*() {
  var user = yield new User({name: 'Bob', password: '12345' });
  console.log(user.toJSON());
})();
paglias commented 10 years ago

@rschmukler thanks you! i didn't thought about that