Skip to content

Instantly share code, notes, and snippets.

@sidazhang
Created July 31, 2014 16:04
Show Gist options
  • Save sidazhang/f9ff1345a9dea3c7a7d8 to your computer and use it in GitHub Desktop.
Save sidazhang/f9ff1345a9dea3c7a7d8 to your computer and use it in GitHub Desktop.
bookshelf
// format and parse (turning snakecase into camelcase and vice versa)
var S = require('string')
var _ = require('underscore')
var format = function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[S(key).underscore().s] = val
console.log(memo)
return memo;
}, {});
}
var parse = function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[S(key).camelize().s] = val
console.log('parse')
return memo;
}, {});
}
// model here
var knex = require('knex')({
client: 'pg',
connection: 'postgres://localhost:5432/bookshelf',
debug: true
});
var bookshelf = require('bookshelf')(knex);
var Account = bookshelf.Model.extend({
tableName: 'account',
transactions: function() {
return this.hasMany(Transactions, 'transactionId');
},
idAttribute: 'accountId',
format: format,
parse: parse
});
// actual code:
var acc = new Account({
accountId: Math.random()
})
acc.save().exec(function(err, model) {
console.log(err, model)
})
/*
This generates the following query:
sql: 'update "account" set "account_id" = $1 where "accountId" = $2',
There are 2 problems:
1. Why is this an update?
2. Why is where "accountId" = $2' <- still camelcase?
*/
CREATE TABLE account (
-- Notice that this is a client-side generated primary key
account_id VARCHAR(255) NOT NULL PRIMARY KEY,
balance BIGINT NOT NULL DEFAULT 0 CHECK(balance >=0)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment