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

喜你入骨 提交于 2019-12-12 01:59:06

问题


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


来源:https://stackoverflow.com/questions/35097304/how-to-dynamically-create-and-expose-a-new-rest-endpoint-in-code-on-the-fly-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!