-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
42 lines (39 loc) · 1.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const _ = require('lodash')
/**
* Case Converter Plugin
*
* Handles the conversion between the database's snake_cased and a model's camelCased properties automatically. You just
* need to load it somewhere in your code.
*
* @example
* var bookshelf = Bookshelf(knex);
* bookshelf.plugin('case-converter');
*
* @module plugins/case-converter
*/
module.exports = function caseConverter(bookshelf) {
const prototype = bookshelf.Model.prototype
/**
* Monkey-patched Model class.
* @extends Model
*/
bookshelf.Model = bookshelf.Model.extend({
/**
* Converts attribute keys to camel case when fetching data from the database.
* @override
*/
parse(attrs) {
const parsedAttributes = prototype.parse.apply(this, arguments)
return _.mapKeys(parsedAttributes, (value, key) => _.camelCase(key))
},
/**
* Converts attribute keys to snake case just before saving a model to the database. The converted attributes
* will not be set on the model.
* @override
*/
format(attrs) {
const parsedAttributes = prototype.format.apply(this, arguments)
return _.mapKeys(parsedAttributes, (value, key) => _.snakeCase(key))
}
})
}