peteut / hapi-shelf

Hapi plugin for bookshelf
4 stars 4 forks source link

Camel casing timestamps #10

Open shinzui opened 8 years ago

shinzui commented 8 years ago

Bookshelf models with hasTimestamps: true should include the updated_at and created_at attributes in the hash attribute of the format and parse methods.

peteut commented 8 years ago

@shinzui thanks for the hint. I'll have a look.

peteut commented 8 years ago

@shinzui Is this excerpt from bookshelf #1155 required to fix hasTimestamps?

  // snake_case to camelCase for working
  parse: function(attrs) {
      return _.reduce(attrs, function(memo, val, key) {
      var boolPrefixes = ['is_','has_','are_','will_','may_','should_'];
      boolPrefixes.forEach(function(prefix) {
        if (_.str.startsWith(key, prefix) && !_.str.endsWith(key, "_at")) {
          val = (val === null) ? null : Boolean(val);
        }
      });
        memo[_.str.camelize(key)] = val;
        return memo;
      }, {});
  },

  // camelCase to snake_case for saving
  format: function(attrs) {
    return _.reduce(attrs, function(memo, val, key) {
      // if the attribute starts with a bool prefix and doesn't end with a timestamp suffix, make it a boolean
      var boolPrefixes = ['is_','has_','are_','will_','may_','should_'];
      boolPrefixes.forEach(function(prefix) {
        if (_.str.startsWith(key, prefix) && !_.str.endsWith(key, "_at")) {
          val = Boolean(val);
        }
      });
      if (key == 'line1') key = 'Line_1';
      if (key == 'line2') key = 'Line_2';
      memo[_.str.underscored(key)] = val;
      return memo;
    }, {});
  },
shinzui commented 8 years ago

@peteut hmm, that looks too complicated. Isn't it enough to introspect hasTimestamps attribute on the model and include those attributes based on its value?

peteut commented 8 years ago

Yes, I think so too. I'll add a unittest to cover hasTimestams = true.