Multitenant get headers inside model boot()


#1

Hi guys,
In my previous experience with lumen PHP for multitenant project i access to headers inside model for change on fly the table string inside the model because each tenants have a dedicated postgres schema (Same connection). Could you suggest any solutions?

Best regards


#2

I can’t access to ctx inside Model boot() or get table()
I think this can be a solution:

  1. At first time set the header with name “tenant” inside the request (i use axios interceptor and nuxt/vue front end

    $axios.onRequest(config => {
    config.headers.tenant = store.state.auth.authUser.currentTenant;
    })

  2. create a key into app Config file with name currentTenant (in adonis app)

    module.exports = {
    /*
    |--------------------------------------------------------------------------

    App Key
    App key is a randomly generated 16 or 32 characters long string required
    to encrypted cookies, sessions and other sensitive data.

    */
    appKey: Env.get(‘APP_KEY’),
    currentTenant: ‘’,

    http: {

  3. create a middleware that use cost Config and before next() store ctx.headers().tenant inside app.currentTenant

    class setTenant{
    async handle ({ request, auth }, next) {
    Config.set(‘app.currentTenant’,request.headers().tenant)
    await next()
    }
    }
    module.exports = setTenant

  4. Finally, in model get table function get the currentTenant variable from Config and prepand this tothe table name

    const Model = use(‘Model’)
    const Config = use(‘Config’)

    class Customer extends Model {

     static get table () {
         return Config.get('app.currentTenant')+'.customers'
     }
    

do you think it can be a good solution?
Regards, Paul