Skip to content
This repository has been archived by the owner on Aug 5, 2021. It is now read-only.

Commit

Permalink
field name convert functions #72
Browse files Browse the repository at this point in the history
  • Loading branch information
PhilWaldmann committed Aug 29, 2018
1 parent 8386268 commit 9a8690c
Show file tree
Hide file tree
Showing 15 changed files with 260 additions and 20 deletions.
2 changes: 2 additions & 0 deletions docs/setup.md
Expand Up @@ -41,6 +41,8 @@ The `Store` constructor takes the following config parameter:
* **autoSave**: Set the default value for `autoSave` on all [relations](./definition#relations)
* **inflection**: OPENRECORD will take your model name and pluralizes it to get e.g. the table name with the help of the [inflection](https://github.com/dreamerslab/node.inflection) module
If you want to overwrite certain names, pass an object with the format `{'wrong name': 'right name'}`.
* **externalAttributeName**: A function to convert field names into another format. e.g. from DB's snake_case to camelCase. The method takes a `string` and expects a `string` as return value.
* **internalAttributeName**: Similar to `externalAttributeName`, but for the reverse
* **plugins**: Array of plugins (See [Plugins](./plugins.md))
* **models**: Array of models (See [Definition](./definition.md#model-definition))
* **migrations**: Array of migrations (See [Migrations](./migrations.md))
Expand Down
40 changes: 31 additions & 9 deletions lib/base/attributes.js
Expand Up @@ -11,6 +11,20 @@ exports.store = {
Error.apply(this)
this.message = 'Unknown attribute type "' + type + '"'
})
},

toInternalAttributeName: function(name){
if(typeof this.config.internalAttributeName === 'function'){
return this.config.internalAttributeName(name)
}
return name
},

toExternalAttributeName: function(name){
if(typeof this.config.externalAttributeName === 'function'){
return this.config.externalAttributeName(name)
}
return name
}
}

Expand Down Expand Up @@ -55,6 +69,7 @@ exports.definition = {

Object.assign(options, fieldType.defaults)

options.name = this.store.toExternalAttributeName(name)
options.type = fieldType
options.writable =
options.writable === undefined ? true : !!options.writable
Expand All @@ -72,7 +87,7 @@ exports.definition = {
name,
options.setter ||
function(value) {
this.set(name, value)
this.set(options.name, value)
}
)

Expand All @@ -91,6 +106,7 @@ exports.definition = {
},

cast: function(attribute, value, castName, record) {
attribute = this.store.toInternalAttributeName(attribute)
castName = castName || 'input'
var attr = this.attributes[attribute]
var cast = attr ? attr.type.cast[castName] : null
Expand Down Expand Up @@ -132,7 +148,9 @@ exports.definition = {
* @return {Definition}
*/
getter: function(name, fn, internal) {
const externalName = this.store.toExternalAttributeName(name)
this.instanceMethods.__defineGetter__(name, fn)
if(externalName !== name) this.instanceMethods.__defineGetter__(externalName, fn)
if (!internal) this.definedGetter[name] = fn

return this
Expand All @@ -149,8 +167,9 @@ exports.definition = {
* @return {Definition}
*/
setter: function(name, fn) {
const externalName = this.store.toExternalAttributeName(name)
this.instanceMethods.__defineSetter__(name, fn)

if(externalName !== name) this.instanceMethods.__defineSetter__(externalName, fn)
return this
},

Expand All @@ -165,13 +184,14 @@ exports.definition = {
* @return {Definition}
*/
variant: function(name, fn) {
const _name = this.store.toInternalAttributeName(name)
const Store = require('../store')
if (!this.attributes[name]) throw new Store.UnknownAttributeError(name)
if (!this.attributes[_name]) throw new Store.UnknownAttributeError(name)

this.attributes[name].variant = fn
this.attributes[_name].variant = fn

this[name + '$'] = function(args) {
return fn.call(this, this[name], args)
return fn.call(this, this[_name], args)
}

return this
Expand Down Expand Up @@ -221,12 +241,14 @@ exports.record = {

for (var field in this.definition.attributes) {
if (this.definition.attributes.hasOwnProperty(field)) {
if (singleAssign && values[field] === undefined) {
var definition = this.definition.attributes[field]
var fieldName = castType === 'input' ? definition.name : field

if (singleAssign && values[fieldName] === undefined) {
continue
}

var definition = this.definition.attributes[field]
value = values[field]
value = values[fieldName]

if (!singleAssign && value && typeof definition.setter === 'function') {
definition.setter.call(this, value)
Expand Down Expand Up @@ -425,7 +447,7 @@ exports.record = {
resetChanges: function() {
for (var name in this.changes) {
if (this.changes.hasOwnProperty(name)) {
this[name] = this.changes[name][0]
this.attributes[name] = this.changes[name][0]
}
}

Expand Down
13 changes: 11 additions & 2 deletions lib/base/conditions.js
Expand Up @@ -95,7 +95,7 @@ exports.model = {
where: function() {
const Utils = this.definition.store.utils
const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy!

const existingConditions = self.getInternal('conditions') || []
const existingMap = {}

Expand All @@ -111,10 +111,16 @@ exports.model = {
existingMap[key] = true
})

var attributeNames = Object.keys(self.definition.attributes)

attributeNames = attributeNames.concat(attributeNames.map(function(name){
return self.definition.attributes[name].name
}))

const parentRelations = self.getInternal('parent_relations')
const conditions = Utils.toConditionList(
Utils.args(arguments),
Object.keys(self.definition.attributes)
attributeNames
)

conditions.forEach(function(cond) {
Expand All @@ -137,6 +143,9 @@ exports.model = {
cond.value.$parents = parentRelations
}
}

if(cond.attribute) cond.attribute = self.store.toInternalAttributeName(cond.attribute)

const key =
cond.type +
'|' +
Expand Down
4 changes: 2 additions & 2 deletions lib/base/inspect.js
Expand Up @@ -37,7 +37,7 @@ exports.model = {
var attributes = []
for (var name in this.definition.attributes) {
if (this.definition.attributes.hasOwnProperty(name)) {
attributes.push(name)
attributes.push(this.definition.attributes[name].name)
}
}

Expand Down Expand Up @@ -77,7 +77,7 @@ exports.record = {
if (value && typeof value.inspect === 'function')
value = value.inspect()
else value = JSON.stringify(value)
attributes.push(name + ':' + value)
attributes.push(this.definition.attributes[name].name + ':' + value)
}
}

Expand Down
8 changes: 7 additions & 1 deletion lib/base/json.js
Expand Up @@ -36,8 +36,14 @@ exports.record = {
) {
tmp[name] = definition.cast(name, tmp[name], 'output', this)

if (tmp[name] && typeof tmp[name].toJson === 'function')
if (tmp[name] && typeof tmp[name].toJson === 'function'){
tmp[name] = tmp[name].toJson()
}

// convert to external names
var value = tmp[name]
delete tmp[name]
tmp[definition.attributes[name].name] = value
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/base/relations/bulk_fetch.js
Expand Up @@ -100,10 +100,10 @@ exports.definition = {
exclude: ['relation', 'relation_to']
})
}

const promise = query.then(function(result) {
// overwrite cache result
relationCache[options.name] = result
relationCache[options.name] = result
return result
})

Expand Down
2 changes: 1 addition & 1 deletion lib/base/relations/has_many.js
Expand Up @@ -53,7 +53,7 @@ exports.definition = {
const key = targetPrimaryKeys[0]

definition.attribute(
inflection.singularize(name) + '_' + inflection.pluralize(key),
definition.store.toExternalAttributeName(inflection.singularize(name) + '_' + inflection.pluralize(key)),
Array,
{
hidden: true,
Expand Down
2 changes: 1 addition & 1 deletion lib/base/validations.js
Expand Up @@ -42,7 +42,7 @@ exports.definition = {
if (!Array.isArray(fields)) fields = [fields]

for (var i in fields) {
var attr = fields[i]
var attr = this.store.toInternalAttributeName(fields[i])
this.validations[attr] = this.validations[attr] || []
this.validations[attr].push(fn)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/stores/sql/order.js
Expand Up @@ -29,7 +29,7 @@ exports.model = {

for (var i in columns) {
self.addInternal('order', {
column: columns[i],
column: self.store.toInternalAttributeName(columns[i]),
order: desc ? 'DESC' : 'ASC'
})
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "openrecord",
"version": "2.1.1",
"version": "2.2.0",
"description": "Active record like ORM for nodejs",
"license": "MIT",
"keywords": [
Expand Down

0 comments on commit 9a8690c

Please sign in to comment.