#7793 sortByWeight #3020

Open
jsegarra wants to merge 7 commits from 7793_sortByWeight into dev
2 changed files with 39 additions and 0 deletions

View File

@ -2,6 +2,7 @@
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const UserError = require('vn-loopback/util/user-error');
const utils = require('loopback/lib/utils');
const {orderBySearch, findLikeKeys} = require('../../util/orderBySearch');
module.exports = function(Self) {
Self.ParameterizedSQL = ParameterizedSQL;
@ -45,6 +46,16 @@ module.exports = function(Self) {
const {result} = ctx;
const length = Array.isArray(result) ? result.length : result ? 1 : 0;
if (length >= this.app.orm.selectLimit) throw new UserError('Too many records');
const likeKeys = findLikeKeys(ctx.args.filter?.where) ?? [];
if (!likeKeys.length) return result;
let property = likeKeys[0].property;
let value = likeKeys[0].value;
if (likeKeys.length > 1) {
const firstOrderBy = likeKeys.find(({prop}) => ctx.args.order[0] === prop);
if (firstOrderBy) property = firstOrderBy.property;
}
return orderBySearch(result, property, value);
});
// Register field ACL validation

View File

@ -0,0 +1,28 @@
exports.orderBySearch = function(results, property, searchValue) {
return results.sort((a, b) => {
const aStartsWithSearch = a[property].startsWith(searchValue);
const bStartsWithSearch = b[property].startsWith(searchValue);
if (aStartsWithSearch && !bStartsWithSearch) return -1;
if (!aStartsWithSearch && bStartsWithSearch) return 1;
return a[property].localeCompare(b[property]);
});
};
exports.findLikeKeys = function(where) {
const likeKeys = [];
function searchLike(obj, parentKey = '') {
if (typeof obj !== 'object' || obj === null) return;
for (const key in obj) {
if (key === 'like')
likeKeys.push({property: parentKey, value: obj[key].replace(/%/g, '')});
else if (typeof obj[key] === 'object')
searchLike(obj[key], key);
}
}
searchLike(where);
return likeKeys;
};