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"?
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
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
firstmethod overfetch.The difference is,
fetchreturns an array andfirstreturns an object.