From 5fe1f80ac1797c32634c749569484be6fb5330f4 Mon Sep 17 00:00:00 2001 From: Bo Lingen Date: Wed, 9 Aug 2017 21:28:43 +0000 Subject: [PATCH] feat: add `getRaw()` & `setRaw()` --- src/index.js | 12 ++++++++++++ src/model.js | 50 +++++++++++++++++++++++++++++++++----------------- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/src/index.js b/src/index.js index 3195011..4317dcd 100644 --- a/src/index.js +++ b/src/index.js @@ -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) diff --git a/src/model.js b/src/model.js index 1f3023e..8a2895f 100644 --- a/src/model.js +++ b/src/model.js @@ -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) { @@ -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) +}