Skip to content

Commit

Permalink
feat: add getRaw() & setRaw()
Browse files Browse the repository at this point in the history
  • Loading branch information
Bo Lingen committed Aug 9, 2017
1 parent ab5cd7b commit 5fe1f80
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 17 deletions.
12 changes: 12 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ class Trilogy {
return model.set(column, criteria, value)
}

getRaw (location, criteria, defaultValue) {
const [table, column] = location.split('.', 2)
const model = checkModel(this, table)
return model.getRaw(column, criteria, defaultValue)
}

setRaw (location, criteria, value) {
const [table, column] = location.split('.', 2)
const model = checkModel(this, table)
return model.setRaw(column, criteria, value)
}

incr (location, criteria, amount) {
const [table, column] = location.split('.', 2)
const model = checkModel(this, table)
Expand Down
50 changes: 33 additions & 17 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,27 +123,19 @@ export default class Model {
}

get (column, criteria, defaultValue) {
return this.findOne(criteria)
.then(data => {
if (!data) return defaultValue
if (typeof data[column] === 'undefined') {
return defaultValue
}

return data[column]
})
return baseGet(this, column, criteria, defaultValue)
}

set (column, criteria, value) {
if (!this.schema[column]) {
throw new Error(
`no column by the name '${column}' is defined in '${this.name}'`
)
}
return baseSet(this, column, criteria, value)
}

return this.update(criteria, {
[column]: value
})
getRaw (column, criteria, defaultValue) {
return baseGet(this, column, criteria, defaultValue, { raw: true })
}

setRaw (column, criteria, value) {
return baseSet(this, column, criteria, value, { raw: true })
}

incr (column, criteria, amount) {
Expand Down Expand Up @@ -244,3 +236,27 @@ export default class Model {
})
}
}

function baseGet (model, column, criteria, defaultValue, options) {
return model.findOne(criteria, options)
.then(data => {
if (!data) return defaultValue
if (typeof data[column] === 'undefined') {
return defaultValue
}

return data[column]
})
}

function baseSet (model, column, criteria, value, options) {
if (!model.schema[column]) {
throw new Error(
`no column by the name '${column}' is defined in '${model.name}'`
)
}

return model.update(criteria, {
[column]: value
}, options)
}

0 comments on commit 5fe1f80

Please sign in to comment.