Lucid: Hide columns from relationship JSON return

Created on 12 Jul 2018  路  3Comments  路  Source: adonisjs/lucid

Hi!
I'm using the adonis-acl (unnoficial package for ACL) and I've a route that returns me the logged User and his role.

const user = await User.query().where('id', auth.user.id).with('roles').fetch()
return user 

So, it returns to me:

[
    {
        "id": 1,
        "username": "hectorgrecco",
        "email": "[email protected]",
        "roles": [
            {
                "id": 1,
                "slug": "admin",
                "name": "Administrador",
                "description": "Administrador do sistema",
                "created_at": "2018-07-12 08:18:56",
                "updated_at": "2018-07-12 08:18:56",
                "pivot": {
                    "role_id": 1,
                    "user_id": 1
                }
            }
        ]
    }
]

The adonis-acl package gives me the method "getRoles()" that returns to me an array of the roles name, but how to "merge" the results and gives me one unique JSON? Like:

[
    {
        "id": 1,
        "username": "hectorgrecco",
        "email": "[email protected]",
        "roles": ["admin", "moderator", "student"]
    }
]

And... how can I hide the "pivot" object, or show just an array of "roles.slug"?

Most helpful comment

You will have to further process the data and convert it to an array. Also since you are pulling roles for a single user, I suggest using first method over fetch.

The difference is, fetch returns an array and first returns an object.

const user = await User.query().where('id', auth.user.id).with('roles').first()
const userJSON = user.toJSON()

userJSON.roles = userJSON.roles.map((role) => role.slug)

return userJSON

All 3 comments

You will have to further process the data and convert it to an array. Also since you are pulling roles for a single user, I suggest using first method over fetch.

The difference is, fetch returns an array and first returns an object.

const user = await User.query().where('id', auth.user.id).with('roles').first()
const userJSON = user.toJSON()

userJSON.roles = userJSON.roles.map((role) => role.slug)

return userJSON

Thank you so very much, @thetutlage!!!!

Closing since not actionable

Was this page helpful?
0 / 5 - 0 ratings