Skip to content

Instantly share code, notes, and snippets.

@joepie91
Forked from nootanghimire/promises.js
Last active October 23, 2015 04:50
Show Gist options
  • Save joepie91/1e765fad739083079c85 to your computer and use it in GitHub Desktop.
Save joepie91/1e765fad739083079c85 to your computer and use it in GitHub Desktop.
var promisify = require("es6-promisify"); // you can also look for a promisifyAll equivalent, but for the sake of demonstration
function findText(freeText, result) {
var query = {
index: result.teamUnique + "_team",
type: result.username,
body: {
query: {
match: {
name: freeText
}
}
}
}
return elasticsearch_client.search(query);
}
exports.findResultsByFreeText = function(req, res, next, freeText) {
//TODO: Check if request contains facet params, and filter accordingly
tryPromise(function() { // https://gist.github.com/joepie91/255250eeea8b94572a03
return getListOfTeams(req.user.username);
}).then(function(results) {
return promiseMap(findText.bind(null, freeText), results);
}).then(function(searchResults) {
req.results = searchResults;
next();
}).catch(function(err) {
// you should normally not log this here, but let it be handled by express-promise-router instead
console.log("An error occurred somewhere:", err);
});
});
var getListOfTeams = function(username) {
return tryPromise(function() {
if(!username){
throw new Error("An error message goes here"); // an object is not an Error!
}
var findMethod = promisify(TeamsToUsers.find).bind(TeamsToUsers); // this would be a lot nicer with promisifyAll...
return findMethod({
username: username
});
}).catch(function(err) {
// you'd ideally want to filter by error type here, but that's not really possible with ES6 promises...
throw new Error("User not found"); // again, object != Error
})
}
@nootanghimire
Copy link

I understood bits and pieces. Will likely get further queries answered on IRC tomorrow. Thanks!

@nootanghimire
Copy link

@joepie91, in line 24 , how does each result entry gets binded to findText() ? Will you explain this a little bit? Thanks :)

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