问题
Basically what the title asks. I'm wondering if it's possible to create a a custom view model in Loopback that is datasource ignorant?
My current process has been to create a view in MySQL, and then build a model in Loopback that overlays the view, but I recently realized that if we decide to migrate to a different back end, or change the datasource somehow, we'd have to figure out how to recreate the view.
Google searches on this have revealed bupkis, so I figured I'd throw it out here to see if anyone has knowledge on the topic.
Thanks in advance!
回答1:
Using views in Loopback works well. Just treat the view as if it were a table and Loopback will treat it the same way. In fact you can actually perform some write operations against the view if you want to. Assuming you have already created the view in SQL here's a snippet to create end-points from an existing table or view in Loopback:
/**
* Creates a REST endpoint using the persistedModel.
* @function createPersistedModelApi
*/
function createPersistedModelApi(app, dataSourceName: string, tablename: string, callback) {
let eventInfo: Type.Event
let ds = app.datasources[dataSourceName];
ds.discoverSchema(tablename, null, function(err, schema) {
if (!err) {
// Set the key field.
schema.properties.rowid.id = true;
// Get a list of the fields
var fields = Object.keys(schema.properties);
// Set some properties on all fields.
fields.forEach(function(field) {
schema.properties[field].required = false;
schema.properties[field].nullable = true;
});
// Create the model.
ds.createModel(tablename,
schema.properties,
{
plural: tablename,
core: true,
base: "PersistedModel",
idInjection: false
}
)
// Get an instance of the model.
let model = ds.getModel(tablename);
// Make the model public with a REST API.
app.model(model, { dataSource: dataSourceName, public: true });
// Error
} else {
....
}
// Return
........
});
}
来源:https://stackoverflow.com/questions/37393839/how-to-create-data-view-models-in-loopback