I'm new to loopback so here is my question:
i have a model called "config-tables" with the following test data:
[
{
ID: 0,
CONFIG_NAME: "MainColor",
DATA_TYPE: "color",
CONFIG_VALUE: "#FF0000",
VERSION: 1
},
{
ID: 1,
CONFIG_NAME: "MainColor",
DATA_TYPE: "color",
CONFIG_VALUE: "#FF00FF",
VERSION: 2
}
]
I want to create two custom methods and expose them to the API:
the first, a method to get the latest version.
the second, a method to get all data of the latest version, version=2 in this case.
i've read a lot about loopback filters but cannot figure how to use something similar to MAX
or TOP
in SQL.
Maybe there's something better to do - but I would simply create two remote methods in /common/models/config-tables.js in order to get the last element of your config-table entity ordered by VERSION attribute:
'use strict';
module.exports = function (configTable) {
//first
configTable.getLastVersion = function (cb) {
// find only one configTable ordered by version
configTable.findOne({order: 'VERSION DESC'}, function (err, config) {
if(config && config.VERSION) {
cb(err, config.VERSION);
} else {
// or throw a new error, depending on what you want
cb(err, 0);
}
});
};
configTable.remoteMethod('getLastVersion', {
returns: {arg: 'VERSION', type: 'number'},
http: {verb: 'get'}
});
//second (depending on the first method)
configTable.getLatests = function (cb) {
configTable.getLastVersion(function (err, last_version) {
if(err || !last_version || last_version === 0) {
// maybe throw error here
return cb(new Error("No config found actually..."));
} else {
// find all configTables where VERSION = last version
configTable.find({where: {VERSION: last_version}}, function (err, configs) {
cb(err, configs);
});
}
});
};
configTable.remoteMethod('getLatests', {
returns: {arg: 'configTables', type: 'object'},
http: {verb: 'get'}
});
};