How to retrieve common values (IpAddress, TenantId) in GenericDao?

460 Views Asked by At

We are using the Play! framework for HTTP sessions.

tenantId and ipAddress are columns that are common across multiple tables.

When the user is logged in, we are storing the tenantId in HttpContextSession

Whenever we require the ip address of the user we are using Http.Context.current().request().remoteAddress() to store the ip address.

We have huge set of queries written and now we want to save or query in a generic way for tenantId.

All the queries goes via GenericDao

Can we use the following in GenericDao to get tenant Id so that we can append in all queries?

Http.Context.session().get("tenantId");

what would be the best approach to save or retrieve these details?

Thanks.

1

There are 1 best solutions below

0
Josh Chappelle On

You don't want your DAO to have to depend on presentation layer things like an HTTP session. I would recommend an abstraction to hide these details.

Create an interface called TenantIdProvider and inject it into your DAO. It would look something like this:

public interface TenantIdProvider
{
    String getTenantId();
}

Then create an implementation called HttpSessionTenantIdProvider.

class HttpSessionTenantIdProvider implements TenantIdProvider
{
    @Override
    public String getTenantId()
    {
        return Http.Context.session().get("tenantId");
    }
}

Now your GenericDAO can have a reference to TenantIdProvider and every query that needs the tenantId can get it through the TenantIdProvider and not have any dependency on the play framework or any other presentation layer that you use.

This really becomes important if you end up having scheduled jobs that run and send notifications or some other task, and they use this DAO. If this DAO depended on an HTTP session it would not be possible. Your job app could create a TenantIdProvider that just returned "system" or something like that.