How to Dynamically Create and Expose a New REST En

2019-09-02 19:19发布

问题:

We're developing a SaaS accounting product that uses the Loopback REST framework and allows authenticated end users to create new tables in their own database instance (MySQL or PostgreSQL).

QUESTION: How can we create a new root level Looback REST endpoint in code (on the fly) to access the new table? For example if the user adds a new table named 'cars' we need to expose a new root level REST endpoint in code called '/api/cars' that uses the persisted model to provide full CRUD capability without restarting the Node.js instance and without writing JSON files to disk.

NOTE: This question is similar to LoopBack: How to Dynamically Create Custom REST Endpoints In Code (On The Fly). However that question and answer only dealt with the creation of a new model in code and did not address how to expose a new, custom root level REST endpoint to access a new model.

I found this interesting post that seems to be headed in the right direction, but we're not sure how to create a new root REST endpoint and then wire it to a dynamically generated model. Also, we're using Kendo rather than Angular:

angular.module('my-app-module')
  .config(function(LoopBackResourceProvider) {
    // Change the URL where to access the LoopBack REST API server
    LoopBackResourceProvider.setUrlBase('http://api.example.com/');
  });

回答1:

All you need to do is create a new model on the fly attached to a datasource. Once the model is created, all endpoints will be available to hit it!

var ds = app.datasources['my-data'];
ds.createModel('Car', {
  model: String,
  make: String,
  year: number
});


回答2:

Here's the solution we ended up with:

// server\boot.js

var ds = app.datasources['mysql'];    
ds.createModel('transactiontype', {
    rowid: {
        type: Number,
        id: true
    },
    transactiontypeid: String,
    description: String,
    active: Number
});    
let model = ds.getModel('transactiontype');    
app.model(model, { public: true });