Providing a custom data source for each tenant
Use case
We need to access the data from different data sources for different tenants. For example, we are the platform for the online website builder, and each client can only view their data. The same data model is used for all clients.Configuration
Each client has its own database. In this recipe, theMango Inc tenant keeps
its data in the remote ecom database while the Avocado Inc tenant works with
the local database (bootstrapped in the docker-compose.yml file) which has the
same data model.
To enable multitenancy, use the
contextToAppId function to
provide distinct identifiers for each tenant. Also, implement the
driverFactory function where
you can select a data source based on the tenant name.
JSON Web Token includes information about the tenant name in
the tenant property of the securityContext.
Query
To get users for different tenants, we will send two identical requests with different JWTs. Also, we send a query with unknown tenant to show that he cannot access to the data model of other tenants.Result
We have received different data from different data sources depending on the tenant’s name:Source code
Please feel free to check out the full source code or run it with thedocker-compose up command. You’ll see the result, including
queried data, in the console.