【问题标题】:Execute raw query on MySQL Loopback Connector在 MySQL Loopback Connector 上执行原始查询
【发布时间】:2016-05-19 02:19:05
【问题描述】:

如何通过带有强循环的 REST API 执行原始查询并公开结果?

我已经阅读了一些关于使用 hooksdataSource.connector.query() 的内容,但我找不到任何工作示例。

【问题讨论】:

    标签: mysql node.js loopbackjs strongloop


    【解决方案1】:

    这是一个基本示例。如果您有产品模型 (/common/models/product.json),请通过添加 /common/models/product.js 文件来扩展模型:

    module.exports = function(Product) {
    
        Product.byCategory = function (category, cb) {
    
            var ds = Product.dataSource;
            var sql = "SELECT * FROM products WHERE category=?";
    
            ds.connector.query(sql, category, function (err, products) {
    
                if (err) console.error(err);
    
                cb(err, products);
    
            });
    
        };
    
        Product.remoteMethod(
            'byCategory',
            {
                http: { verb: 'get' },
                description: 'Get list of products by category',
                accepts: { arg: 'category', type: 'string' },
                returns: { arg: 'data', type: ['Product'], root: true }
            }
        );
    
    };
    

    这将创建以下端点示例:GET /Products/byCategory?group=computers

    http://docs.strongloop.com/display/public/LB/Executing+native+SQL

    【讨论】:

    • 错别字很少:Product.byGroup 应该是Product.byCategory"SELECT * FROM products 应该是"SELECT * FROM products
    • 你能提供一个如何在数据库中存储模型的例子吗?我的意思是,如何创建一个新的Product 然后插入
    • 还有.. 另一个问题,SQL 注入呢?
    • docs.strongloop.com/display/public/LB/Executing+native+SQL This feature has not been fully tested and is not officially supported: the API may change in future releases. In general, it is always better to perform database actions through connected models. Directly executing SQL may lead to unexpected results, corrupted data, and other issues. 为什么文档会这样说明?
    • 我尝试了一个具有完全相同代码的示例,但发现上述示例存在很多问题,对于我的情况,postgresql 不接受“?”,它将接受“$1,$2”而不是“?”并且 params 必须是数组对象 ex。变量参数 = [];参数.push(st1);参数.push(st2);
    【解决方案2】:
    1. 在您的/common/models/model.js 中公开一个远程方法
    2. 在远程方法中执行sql查询(通过dataSource.connector.query(sql, cb);

    【讨论】:

    • 如果您只想在新模型上使用一个远程方法怎么办?在那种情况下,我猜根据您的建议,您将不得不使用 disableRemoteMethod 禁用所有默认远程方法,例如 find、updateAll 等,对吧?
    • 是的,我相信这是 ATM 的唯一途径。我认为这是我们需要使 LoopBack 3 更容易的事情,因为我过去曾看到多个请求禁用所有或仅允许 n 个远程方法等功能。请参阅github.com/strongloop/loopback/issues/…
    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多