Skip to content

Commit

Permalink
test(qb): add findOrFail method
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Nov 14, 2023
1 parent 5cd3b61 commit f3d271e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
19 changes: 19 additions & 0 deletions src/models/builders/ModelQueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { Model } from '#src/models/Model'
import type { Driver } from '#src/drivers/Driver'
import { QueryBuilder } from '#src/database/builders/QueryBuilder'
import { ModelGenerator } from '#src/models/factories/ModelGenerator'
import { NotFoundDataException } from '#src/exceptions/NotFoundDataException'

export class ModelQueryBuilder<
M extends Model = any,
Expand All @@ -26,9 +27,27 @@ export class ModelQueryBuilder<
this.generator = new ModelGenerator<M>(this.Model as any)
}

/**
* Find a value in database.
*/
public async find() {
const data = await super.find()

return this.generator.generateOne(data)
}

/**
* Find a value in database or throw exception if undefined.
*/
public async findOrFail() {
const data = await this.find()

if (!data) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
throw new NotFoundDataException(this.Model.connection())
}

return data
}
}
16 changes: 14 additions & 2 deletions tests/unit/models/builders/ModelQueryBuilderTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Database } from '#src/facades/Database'
import { Column } from '#src/models/annotations/Column'
import { FakeDriver } from '#tests/fixtures/drivers/FakeDriver'
import { DatabaseProvider } from '#src/providers/DatabaseProvider'
import { NotFoundDataException } from '#src/exceptions/NotFoundDataException'
import { Test, Mock, AfterEach, type Context, BeforeEach } from '@athenna/test'

class User extends Model {
Expand Down Expand Up @@ -180,13 +181,24 @@ export default class ModelQueryBuilderTest {
@Test()
public async shouldBeAbleToFindDataUsingFindOrFail({ assert }: Context) {
const expectedData = { id: '1', name: 'John Doe' }
Mock.when(FakeDriver, 'findOrFail').resolve(expectedData)
Mock.when(FakeDriver, 'find').resolve(expectedData)

const queryBuilder = User.query()
const result = await queryBuilder.findOrFail()

assert.calledOnce(FakeDriver.findOrFail)
assert.calledOnce(FakeDriver.find)
assert.deepEqual(result, expectedData)
assert.instanceOf(result, User)
}

@Test()
public async shouldThrownNotFoundDataExceptionWhenFindOrFailReturnsUndefined({ assert }: Context) {
Mock.when(FakeDriver, 'find').resolve(undefined)

const queryBuilder = User.query()

await assert.rejects(() => queryBuilder.findOrFail(), NotFoundDataException)
assert.calledOnce(FakeDriver.find)
}

@Test()
Expand Down

0 comments on commit f3d271e

Please sign in to comment.