How is it possible to execute raw query and expose results through REST API with strongloop?
I've read something about using hooks
and dataSource.connector.query()
but I cannot find any working examples.
For LoopBack 3 usersUse the Data source generator to add a MySQL data source to your application. The generator will prompt for the database server hostname, port, and other settings required to connect to a MySQL database. It will also run the npm install command above for you. Edit <DataSourceName>.
LoopBack is an award-winning, highly extensible, open-source Node. js and TypeScript framework based on Express. It enables you to quickly create APIs and microservices composed from backend systems such as databases and SOAP or REST services.
Here is a basic example. If you have a Product model (/common/models/product.json), extend the model by adding a /common/models/product.js file:
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 }
}
);
};
This will create the following endpoint example: GET /Products/byCategory?group=computers
http://docs.strongloop.com/display/public/LB/Executing+native+SQL
/common/models/model.js
dataSource.connector.query(sql, cb);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With