Skip to content

Commit

Permalink
Merge pull request #50 from AthennaIO/develop
Browse files Browse the repository at this point in the history
feat(model): make toJSON execute in relations
  • Loading branch information
jlenon7 authored Nov 12, 2022
2 parents f4ce3e4 + 3ee505d commit 7f6eb00
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 4 deletions.
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": "1.3.3",
"version": "1.3.4",
"description": "The Athenna database handler for SQL/NoSQL.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
25 changes: 24 additions & 1 deletion src/Models/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -507,9 +507,32 @@ export class Model {
* @return {any|any[]}
*/
toJSON() {
const Model = this.constructor

const json = {}
const relations = Model.getSchema().relations.map(relation => relation.name)

Object.keys(this).forEach(key => {
if (relations.includes(key)) {
if (Is.Array(this[key])) {
json[key] = this[key].map(d => {
if (d.toJSON) {
return d.toJSON()
}

return d
})

return
}

Object.keys(this).forEach(key => (json[key] = this[key]))
json[key] = this[key].toJSON ? this[key].toJSON() : this[key]

return
}

json[key] = this[key]
})

return json
}
Expand Down
7 changes: 7 additions & 0 deletions tests/Unit/Models/ProductModelTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -548,4 +548,11 @@ test.group('ProductModelTest', group => {
assert.isUndefined(criterias.select)
assert.isUndefined(criterias.orderBy)
})

test('should be able to transform to json the relations included in the model', async ({ assert }) => {
const product = await ProductMySql.query().includes('user').find()
const productJson = product.toJSON()

assert.notInstanceOf(productJson.user, UserMySql)
})
})
10 changes: 10 additions & 0 deletions tests/Unit/Models/UserModelTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -574,4 +574,14 @@ test.group('UserModelTest', group => {
assert.isUndefined(criterias.select)
assert.isUndefined(criterias.orderBy)
})

test('should be able to transform to json the relations included in the model', async ({ assert }) => {
const { id } = await User.query().find()
await Product.factory().create({ userId: id })

const user = await User.query().includes('products').find()
const userJson = user.toJSON()

assert.notInstanceOf(userJson.products[0], Product)
})
})

0 comments on commit 7f6eb00

Please sign in to comment.