Multiple request controller


#1

Hi,

How can I avoid repeating the same functions?
I retrieve member info on each page.

'use strict'

const Database = use('Database')
const User = use('App/Models/User')

class UserController {

	async index({view, auth}){
		const currentUser = await auth.getUser()
		const user = await currentUser.profile().fetch()
		return view.render('home.index', {user})
	}
    async settings({view, auth}){
		const currentUser = await auth.getUser()
		const user = await currentUser.profile().fetch()
		return view.render('home.settings', {user})
	}
	async otherPage({view, auth}){
		const currentUser = await auth.getUser()
		const user = await currentUser.profile().fetch()
		return view.render('home.otherpage', {user})
	}

}
module.exports = UserController

Thanks


#2

Hey @nikoola! :wave:

You can simply extract those behaviour to another method in your controller.

According to your code, it’d be probably better to simply create a middleware that fill eager load the profile of the authenticated user.


#3

I already tried to create a middleware “GetUser”, I did not succeed :frowning:
The page sends me no data

E_MISSING_CONFIG: auth. GetUser is not defined inside config/auth.js file > More details: https://err.sh/adonisjs/errors/E_MISSING_CONFIG

#4

It should be quite simple.

'use strict'

class ProfileLoading {
  async handle ({ auth }, next) {
    try {
      await auth.user.load('profile')
    } catch (e) {}

    await next()
  }
}

module.exports = ProfileLoading

Then register this middleware as global middleware (run it after the AuthInit).


Auth.user. (other fields)
#5

it does not work

async settings({view}){
	return view.render('home.settings')
}

In the “settings” page, the data is not displayed


#6

You still need to send to your view the authenticated user.

async settings ({ auth, view }) {
  return view.render('home.settings', { user: auth.user })
}

#7

it only works with the users table
I have a profile table, containing user data, I connected the model profile to users

// Models/User.js
  profile () {
    return this.hasOne('App/Models/Profile', 'id', 'user_id')
  }

#8

In the middleware we lazy-loaded the profile relation.

// here
auth.user.load('profile')

This means everywhere in your application you will be able to use auth.user.getRelated('profile').SOMETHING.

In the view, you will be able to use user.profile.SOMETHING.


#9

Thank you, it works;)

but there is a way to shorten the variable:

auth.user.getRelated('profile').surname
?