Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api/main_endpoints/models/User.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const mongoose = require('mongoose');
const mongooseFuzzySearching = require('mongoose-fuzzy-searching');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
const membershipState = require('../../util/constants').MEMBERSHIP_STATE;
Expand Down Expand Up @@ -78,6 +79,10 @@ const UserSchema = new Schema(
{ collection: 'User' }
);

UserSchema.plugin(mongooseFuzzySearching, {
fields: ['firstName', 'lastName', 'email'],
});

UserSchema.pre('save', function(next) {
const member = this;
let emailRegExp = new RegExp(['^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0',
Expand Down
48 changes: 16 additions & 32 deletions api/main_endpoints/routes/ShortcutSearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,14 @@ const logger = require('../../util/logger');
router.post('/', async function(req, res) {
if (!checkIfTokenSent(req)) {
return res.sendStatus(FORBIDDEN);
} else if (!checkIfTokenValid(req, membershipState.OFFICER)) {
} else if (!checkIfTokenValid(req)) {
return res.sendStatus(UNAUTHORIZED);
}

if (!req.body.query) {
return res.status(OK).send({ items: [] });
}

const query = req.body.query.replace(/[*\s]/g, '');

// Create a fuzzy regex pattern to match characters in order, e.g., "pone" -> /p.*o.*n.*e/i
const fuzzyPattern = query.split('').join('.*');
const pattern = new RegExp(fuzzyPattern, 'i');

const maybeOr = {
$or: [
{
$expr: {
$regexMatch: {
input: { $concat: ['$firstName', '$lastName'] },
regex: pattern,
}
}
},
{ email: { $regex: new RegExp(query, 'i')} }
]
};

/**
* Function to calculate scores based on token matches for sorting
* @param {string} str - The string to score against
Expand Down Expand Up @@ -94,17 +74,21 @@ router.post('/', async function(req, res) {
};
};

// Find user and sort results based on best match of full name or email
User.find(maybeOr, { password: 0 })
.limit(5)
.then(items => {
items.sort(sortByMatch(req.body.query));
res.status(OK).send({ items });
})
.catch((error) => {
logger.error('/shortcutsearchusers encountered an error:', error);
res.sendStatus(BAD_REQUEST);
});
try {
const users = await User.find({});
for (const user of users) {
await user.save();
}
const topUsers = await User.fuzzySearch(req.body.query)
.limit(5)
.select('-password, -apiKey');

const sortUsers = topUsers.sort(sortByMatch(req.body.query));

return res.status(OK).send({ items: sortUsers });
} catch (e) {
return res.sendStatus(SERVER_ERROR);
}
});

module.exports = router;
Loading