Skip to content

Commit

Permalink
feat(lucid): add support for findByOrFail
Browse files Browse the repository at this point in the history
just like findOrFail, findByOrFail can also remove lots of clauses
  • Loading branch information
thetutlage committed Aug 12, 2016
1 parent b7f2927 commit 2ec6a52
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Lucid/Model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,25 @@ class Model {
return result
}

/**
* find for a row using key/value pairs
* or fail by throwing an exception.
*
* @method findByOrFail
*
* @param {String} key
* @param {Mixed} value
*
* @return {Object}
*/
static * findByOrFail (key, value) {
const result = yield this.findBy(key, value)
if (!result) {
throw new CE.ModelNotFoundException(`Unable to fetch results for ${key} ${value}`)
}
return result
}

/**
* returns all records for a given model
*
Expand Down
21 changes: 21 additions & 0 deletions test/unit/lucid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,27 @@ describe('Lucid', function () {
expect(user.username).to.equal('bea')
})

it('should throw exception when unable to find a row using key/value pair', function * () {
class User extends Model {
}
try {
yield User.findByOrFail('username', 'koka')
expect(true).to.equal(false)
} catch (e) {
expect(e.name).to.equal('ModelNotFoundException')
expect(e.message).to.equal('Unable to fetch results for username koka')
}
})

it('should be able to find a given record using findByOrFail method', function * () {
class User extends Model {
}
yield User.query().insert({username: 'bea', firstname: 'Bea', lastname: 'Mine'})
let user = yield User.findByOrFail('username', 'bea')
expect(user instanceof User)
expect(user.username).to.equal('bea')
})

it('should be able to find a given record using primary key', function * () {
class User extends Model {
}
Expand Down

0 comments on commit 2ec6a52

Please sign in to comment.