moleculerjs/moleculer-db

Case insensitive search [moleculer-db-adapter-sequelize]

DenisFerrero opened this issue · 1 comments

Rather than Like wouldn't be more useful the iLike pattern? We have many entities called "Machine" and "STATIONS" but when the user searches for "machine" or "stations" he does not find anything here the search logic

I found that iLike is available only in PG so to achieve the same result I created this solution

if (_.isString(params.search) && params.search !== "") {
	let fields = [];
	if (params.searchFields) {
		fields = _.isString(params.searchFields) ? params.searchFields.split(" ") : params.searchFields;
	}

-	const searchConditions = fields.map(f => {
-		return {
-			[f]: {
-				[Op.like]: "%" + params.search + "%"
-			}
-		};
-	});

+	const lowerCaseSearch = "%" + (params.search).toLowerCase() + "%";  
+	const searchConditions = fields.map(f => {
+		return Sequelize.where(
+			Sequelize.fn("lower", Sequelize.col(f)),
+			Op.like,
+			lowerCaseSearch
+		)
+	});

	if (params.query) {
		q.where[Op.and] = [
			params.query,
			{ [Op.or]: searchConditions }
		];
	} else {
		q.where[Op.or] = searchConditions;
	}
	...

This solution seems to work but I have some trouble making the tests work. Can someone help me out with that?