Skip to content

Instantly share code, notes, and snippets.

@sasikanth513
Created November 19, 2018 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sasikanth513/593df16550d3e03dcdc85d8026f32698 to your computer and use it in GitHub Desktop.
Save sasikanth513/593df16550d3e03dcdc85d8026f32698 to your computer and use it in GitHub Desktop.
Peerlyst-search
import { Meteor } from "meteor/meteor";
import { _ } from "meteor/underscore";
import { ValidatedMethod } from "meteor/mdg:validated-method";
import { SimpleSchema } from "meteor/aldeed:simple-schema";
import { DDPRateLimiter } from "meteor/ddp-rate-limiter";
import {
shouldSearchExactWord,
removeQuotesFromWord,
getRegexStringForWordsMatch,
} from "./helpers.js";
import { FEEDS_PER_PAGE } from '/imports/helpers/constants.js';
import { Feeds } from "./feeds.js";
export const search = new ValidatedMethod({
name: "feeds.search",
validate: new SimpleSchema({
text: { type: String, optional: true },
sort: { type: String },
page: { type: Number },
}).validator(),
run({ text, sort, page }) {
let query = {};
let sortQuery = {};
sortQuery[sort] = 1;
const skip = page * FEEDS_PER_PAGE;
const limit = FEEDS_PER_PAGE;
if (text && text.trim() && text.trim().length > 0) {
// if user requests for exact search using double quotes
// then use regular regex search
if (shouldSearchExactWord(text)) {
text = removeQuotesFromWord(text);
} else if (text.split(" ").length > 1) {
// divide the phrase into words and do or regex search
const regexText = getRegexStringForWordsMatch(text);
text = regexText;
}
query = {
$or: [
{ name: { $regex: text, $options: "i" } },
{ description: { $regex: text, $options: "i" } }
]
};
}
const feed = Feeds.find(query, { sort: sortQuery, skip, limit }).fetch();
const total = Feeds.find(query, { sort: sortQuery, skip, limit }).count();
return {
feed,
total,
}
}
});
// Get list of all method names on Feeds
const FEEDS_METHODS = _.pluck([search], "name");
if (Meteor.isServer) {
// Only allow 5 todos operations per connection per second
DDPRateLimiter.addRule(
{
name(name) {
return _.contains(FEEDS_METHODS, name);
},
// Rate limit per connection ID
connectionId() {
return true;
}
},
5,
1000
);
}
@sasikanth513
Copy link
Author

sasikanth513 commented Nov 19, 2018

helpers.js file for reference

export const shouldSearchExactWord = (text) => {
  const firstChar = text[0];
  const lastChar = text[text.length - 1];
  return firstChar === '"' && lastChar === '"';
};

export const removeQuotesFromWord = (text) => {
  return text.slice(1, -1);
};

export const getRegexStringForWordsMatch = (text) => {
  const words = text.split(' ');
  if (words.length === 1) {
    return text;
  }
  // split the words and create regex OR search
  const out = [];
  return words.map(word => word.trim()).filter(word => word).join('|');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment