Created
July 31, 2014 16:04
-
-
Save sidazhang/f9ff1345a9dea3c7a7d8 to your computer and use it in GitHub Desktop.
bookshelf
This file contains 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
// 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? | |
*/ |
This file contains 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
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