Skip to content

Instantly share code, notes, and snippets.

@chrisfrancis27
Created January 25, 2016 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfrancis27/fd3f9ab5fd384bd9ca55 to your computer and use it in GitHub Desktop.
Save chrisfrancis27/fd3f9ab5fd384bd9ca55 to your computer and use it in GitHub Desktop.
Bookshelf hash IDs
'use strict';
const _ = require('lodash');
const bookshelf = require('../config/bookshelf');
const hasher = require('../utils/hasher');
require('./thing');
let Example = Bookshelf.model.extend({
tableName: 'examples',
things() {
// One-to-many
return this
.hasMany('Thing')
.query(qb => qb.orderBy('name', 'asc'))
;
},
// Integer IDs to hashes
// e.g. 8 => "693da7d7"
parse: function(attrs) {
return _.reduce(Base.prototype.parse.call(this, attrs), (memo, val, key) => {
if (key === 'id') {
memo[key] = hasher.encode(val);
} else {
memo[key] = val;
}
return memo;
}, {});
},
// Hash IDs to integers
// e.g. "693da7d7" => 8
format: function(attrs) {
return _.reduce(Base.prototype.format.call(this, attrs), (memo, val, key) => {
if (key === 'id') {
memo[key] = hasher.decode(val)[0];
} else {
memo[key] = val;
}
return memo;
}, {});
}
});
module.exports = bookshelf.model('Example', Example);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment