diginix
diginix

Reputation: 21

Best Practice Advice - Loopback API

I want to make a webservice and it looks like Loopback is good starting point. To explain my question, I will describe situation

I have 2 MySQL Tables:
Users
Companies
Every User has it's Company. It's like master User for it's company.

I wish to create Products table for each company next way:
company1_Products,
company2_Products,
company3_Products

Each company have internal Users, like:
company1_Users,
company2_Users,
company3_Users

Internal users are logging in from corresponding subdomain, like
company1.myservice.com
company2.myservice.com

For the API, I want datasource to get Products from the corresponding table. So the question is, how to change datasource dynamically?

And how to handle Users? Storing in one table is not good, because internal company users could be in different companies...

Maybe there's better way to do such models?

Upvotes: 2

Views: 477

Answers (1)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10795

Disclaimer: I am co-author and one of current maintainers of LoopBack.

how to change datasource dynamically?

The following StackOverflow answer describes a solution how to attach a single model (e.g. Product) to multiple datasources: https://stackoverflow.com/a/28327323/69868 This solution would work if you were creating one MySQL database per company instead of using company's name as the prefix of Product table name.

To achieve what you described, you can use model subclassing. For each company, define a new company-specific Product model inheriting from the shared Product model and changing the table name.

// common/models/company1-product.json
{
  "name": "Company1_Product",
  "base": "Product",
  "mysql": {
    "tableName": "company1_Products"
  }
  // etc.
}

You can even create these models on the fly using app.registry.createModel() and app.model() APIs, and then run dataSource.autoupdate to create SQL tables for the new model(s).

And how to handle Users? Storing in one table is not good, because internal company users could be in different companies...

I suppose you can use the same approach as you do for Products and as you described in your question.

Maybe there's better way to do such models?

The problem you are facing is calling multi-tenancy. I am afraid we haven't figured out an easy to use solution yet. There are many possible ways how to implement multi-tenancy.

For example, you can create one LoopBack application for each Company (tenant) and then create a top-level LoopBack or Express application to route incoming requests to appropriate tenant-specific LB app instance. See the following repository for a proof-of-concept implementation: https://github.com/strongloop/loopback-multitenant-poc

Upvotes: 2

Related Questions