Skip to content

Commit

Permalink
feat(clear): add clear() method, safeguard remove()
Browse files Browse the repository at this point in the history
Add new `clear()` method to remove all objects from the model. Safeguard `remove()` so that empty criteria will not remove all objects.
  • Loading branch information
citycide committed Jan 7, 2017
1 parent 7519f9e commit ab671c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ class Trilogy {
return model.remove(criteria)
}

clear (location) {
let model = checkModel(this, location)
return model.clear()
}

count (location, criteria, options) {
let [table, column] = location.split('.', 2)
let model = checkModel(this, table)
Expand Down
15 changes: 14 additions & 1 deletion src/model.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as types from './types'
import * as helpers from './helpers'
import * as enforcers from './enforcers'
import { isArray, isString } from './util'
import { isArray, isString, isObject } from './util'

export default class Model {
constructor (ctx, name, schema, options) {
Expand Down Expand Up @@ -155,12 +155,25 @@ export default class Model {
}

remove (criteria) {
if (!helpers.isValidWhere(criteria)) {
return Promise.resolve(0)
}

if (isObject(criteria) && !Object.keys(criteria).length) {
return Promise.resolve(0)
}

let query = this.ctx.knex(this.name).del()
query = helpers.buildWhere(query, criteria)

return helpers.runQuery(this.ctx, query)
}

clear () {
let query = this.ctx.knex(this.name).truncate()
return helpers.runQuery(this.ctx, query)
}

count (column, criteria, options = {}) {
if (!isString(column)) {
options = criteria
Expand Down

0 comments on commit ab671c1

Please sign in to comment.