Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/database",
"version": "5.42.0",
"version": "5.43.0",
"description": "The Athenna database handler for SQL/NoSQL.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
48 changes: 48 additions & 0 deletions src/models/BaseModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,54 @@ export class BaseModel {
return this[relation as any]
}

public loadOnly(relation: string): Promise<any>
public loadOnly<K extends ModelRelations<this>>(
relation: K,
closure?: (
query: ModelQueryBuilder<
Extract<this[K] extends BaseModel[] ? this[K][0] : this[K], BaseModel>
>
) => any
): Promise<this[K]>

/**
* Eager load a model relation without mutating
* the current model instance.
*/
public async loadOnly<K extends ModelRelations<this>>(
relation: K | string,
closure?: (
query: ModelQueryBuilder<
Extract<this[K] extends BaseModel[] ? this[K][0] : this[K], BaseModel>
>
) => any
) {
const Model = this.constructor as any
const schema = Model.schema()
const generator = new ModelGenerator(Model, schema)
const copy = new Model()
const relations = schema.getRelationProperties()

Object.keys(this).forEach(key => {
if (relations.includes(key)) {
return
}

copy[key] = Json.copy(this[key])
})

await generator.includeRelation(
copy,
schema.includeRelation(relation, closure)
)

if (relation.includes('.')) {
return Json.get(copy, relation)
}

return copy[relation as any]
}

/**
* Validate if model is persisted in database
* or if it's a fresh instance.
Expand Down
49 changes: 49 additions & 0 deletions tests/unit/models/BaseModelTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Product } from '#tests/fixtures/models/Product'
import { ModelSchema } from '#src/models/schemas/ModelSchema'
import { ModelFactory } from '#src/models/factories/ModelFactory'
import { DatabaseProvider } from '#src/providers/DatabaseProvider'
import { ModelGenerator } from '#src/models/factories/ModelGenerator'
import { ModelQueryBuilder } from '#src/models/builders/ModelQueryBuilder'
import { NotFoundDataException } from '#src/exceptions/NotFoundDataException'
import { Test, type Context, BeforeEach, AfterEach, Mock } from '@athenna/test'
Expand Down Expand Up @@ -500,6 +501,54 @@ export default class BaseModelTest {
assert.deepEqual(json, { id: '1', name: 'lenon', metadata3: 'metadata3' })
}

@Test()
public async shouldBeAbleToLoadOnlyOneObjectRelationFromInstanceWithoutMutatingIt({ assert }: Context) {
Mock.stub(ModelGenerator.prototype, 'includeRelation').callsFake((async (model: any) => {
const userModel = model as User

userModel.profile = new Profile()
userModel.profile.id = '1'

return userModel
}) as any)

const user = new User()

user.id = '1'
user.name = 'lenon'

const profile = await user.loadOnly('profile')

assert.instanceOf(profile, Profile)
assert.isUndefined(user.profile)
assert.deepEqual(user.id, '1')
assert.deepEqual(user.name, 'lenon')
}

@Test()
public async shouldBeAbleToLoadOnlyOneArrayRelationFromInstanceWithoutMutatingIt({ assert }: Context) {
Mock.stub(ModelGenerator.prototype, 'includeRelation').callsFake((async (model: any) => {
const userModel = model as User

userModel.products = [new Product()]
userModel.products[0].id = '1'

return userModel
}) as any)

const user = new User()

user.id = '1'
user.name = 'lenon'

const products = await user.loadOnly('products')

assert.instanceOf(products[0], Product)
assert.isUndefined(user.products)
assert.deepEqual(user.id, '1')
assert.deepEqual(user.name, 'lenon')
}

@Test()
public async shouldBeAbleToValidateThatAModelHasNotBeenPersistedInDatabase({ assert }: Context) {
const user = new User()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,4 +307,13 @@ export default class BelongsToRelationTest {
assert.instanceOf(product.user, User)
assert.instanceOf(profile, Profile)
}

@Test()
public async shouldBeAbleToLoadNestedBelongsToRelationUsingLoadOnlyMethod({ assert }: Context) {
const product = await Product.find()
const profile = await product.loadOnly('user.profile')

assert.isUndefined(product.user)
assert.instanceOf(profile, Profile)
}
}
10 changes: 10 additions & 0 deletions tests/unit/models/relations/HasOne/HasOneRelationTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,14 @@ export default class HasOneRelationTest {
profile: { id: 1, userId: 1 }
})
}

@Test()
public async shouldBeAbleToLoadOneRelationFromInstanceWithoutMutatingTheModel({ assert }: Context) {
const user = await User.query().find()
const profile = await user.loadOnly('profile')

assert.instanceOf(user, User)
assert.instanceOf(profile, Profile)
assert.isUndefined(user.profile)
}
}
Loading