loopback-full-text-search-mysql
Version:
Add Full-text search when using the 'q' parameter in the where clause for Loopback 3
102 lines (99 loc) • 3.55 kB
JavaScript
module.exports = function(app, options) {
const remotes = app.remotes();
const applySearch = function(ctx, next) {
options.models.map(model => {
if ((this.name === model.name) && (model.fields)) {
let fields;
if(ctx.args.filter && ctx.args.filter) {
fields = ctx.args.filter
} else if(ctx.args && ctx.args.where) {
fields = ctx.args;
}
let query;
console.log(ctx.args.where)
if(fields && fields.where) {
query = fields && fields.where
} else {
query = fields && fields.where;
}
let search = {};
let orSearch = {};
let and = [];
let perpetualOr = [];
if (query && query.q) {
if (model.fields.length === 1) {
search = {[model.fields[0]]: {like: `%${query.q}%`}};
} else {
let searches = [];
let i = 0;
model.fields.map(field => {
if(query.q.split(" ").length > 1 && query.q.split(" ").length != i + 1) {
let arr = query.q.split(" ");
arr.map(value => {
searches.push({[field]: {like: `%${value}%`}});
});
let orObject = {or: searches};
and.push(orObject);
searches = [];
i++;
} else {
searches.push({[field]: {like: `%${query.q}%`}});
search = {or: searches};
}
});
if(model.alwaysOr != undefined && model.alwaysOr.length > 0) {
model.alwaysOr.map(orValue => {
if(query.q.split(" ").length > 1 && query.q.split(" ").length != i + 1) {
let arr = query.q.split(" ");
arr.map(value => {
perpetualOr.push({[orValue]: {like: `%${value}%`}});
});
// let orObject = {or: searches};
// and.push(orObject);
// searches = [];
i++;
} else {
perpetualOr.push({[orValue]: {like: `%${query.q}%`}});
// search = {or: searches};
}
});
}
if(and != undefined && and.length > 0) {
if(perpetualOr != undefined && perpetualOr.length > 0) {
perpetualOr.push({and: and});
search = {or: perpetualOr};
} else {
search = {and: and};
}
} else {
if(perpetualOr != undefined && perpetualOr.length > 0) {
console.log(perpetualOr);
perpetualOr.push(search);
search = {or: perpetualOr};
console.log(search);
}
// perpetualOr.p
// search = {}
}
}
// delete fields.where.q;
if(fields.where != undefined) {
delete fields.where.q;
} else {
delete fields.q;
}
if (Object.keys(fields.where).length !== 0) {
search = {and: [search, fields.where]};
}
fields.where = search;
ctx.args.filter = fields;
}
}
});
next();
};
const pattern = ['*.find', '*.count'];
for (let i = pattern.length - 1; i >= 0; i--) {
remotes.before(pattern[i], applySearch);
}
};