From 2ec6a52fed4960818873cb238c5fa828fee513f7 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Fri, 12 Aug 2016 21:34:06 +0530 Subject: [PATCH] feat(lucid): add support for findByOrFail just like findOrFail, findByOrFail can also remove lots of clauses --- src/Lucid/Model/index.js | 19 +++++++++++++++++++ test/unit/lucid.spec.js | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/Lucid/Model/index.js b/src/Lucid/Model/index.js index 37bae3a6..8de1a46c 100644 --- a/src/Lucid/Model/index.js +++ b/src/Lucid/Model/index.js @@ -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 * diff --git a/test/unit/lucid.spec.js b/test/unit/lucid.spec.js index 5c2b9d60..58a48f37 100644 --- a/test/unit/lucid.spec.js +++ b/test/unit/lucid.spec.js @@ -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 { }