How to create data view models in Loopback?

雨燕双飞 提交于 2019-12-23 06:05:01

问题


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

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