Search code examples
restdynamicloopbackjsstrongloop

How to Dynamically Create and Expose a New REST Endpoint In Code (on the fly) for a Custom Loopback Model


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/');
  });

Solution

  • 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 });