Created
January 25, 2016 11:51
-
-
Save chrisfrancis27/fd3f9ab5fd384bd9ca55 to your computer and use it in GitHub Desktop.
Bookshelf hash IDs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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