Skip to content

Instantly share code, notes, and snippets.

@alexbeletsky
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save alexbeletsky/a3ce02a05790e24a3176 to your computer and use it in GitHub Desktop.

Select an option

Save alexbeletsky/a3ce02a05790e24a3176 to your computer and use it in GitHub Desktop.
var express = require('express');
var google = require('google');
var app = express();
function googleSearch(opts, callback) {
var search = config(opts);
var results = [], pages = 0;
search(opts.query, function (err, next, links) {
if (err) {
return callback(err);
}
links = links.map(function (link) {
return {title: link.title, link: link.link, description: link.description};
});
results = results.concat(links);
if (pages < opts.nextPages) {
pages =+ 1;
next();
} else {
callback(null, {query: opts.query, results: results});
}
});
function config(opts) {
google.resultsPerPage = opts.resultsPerPage || 25;
google.tld = opts.tld;
google.lang = opts.lang;
return google;
}
}
app.get('/search', function (req, res, next) {
var query = req.query.query;
var lang = req.query.lang || 'en';
var tld = req.query.tld || 'de';
if (!query) {
return res.status(400).json({message: 'query is missing'});
}
var opts = {
query: query,
lang: lang,
tld: tld,
resultsPerPage: 25,
nextPages: 1
};
googleSearch(opts, function (err, results) {
if (err) {
return next(err);
}
res.json(results);
});
});
app.listen(3322, function () {
console.log('search service started on 3322');
});
{
"name": "yes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.12.3",
"google": "^0.6.0"
}
}
@olimart

olimart commented Mar 24, 2015

Copy link
Copy Markdown

Error object is not a function raised on line 23 next();
Any idea?

@olimart

olimart commented Mar 25, 2015

Copy link
Copy Markdown

Alex, one more thing please.

I'm trying to format the response with not just the results but also query params. Problem is I'm having trouble pushing to the array.

Here is the expected results.
As you can see, I'd like to push search params to results and move search results under results

{
    "search": {
      "query" :  "my-keywords",
      "lang" : "en",
      "ltd" : "de"
    },
    "results" : [
         { "title" : "abc",
          "link" : "//",
          "description" : "blabla"
        },
        { "title" : "abc",
          "link" : "//",
          "description" : "blabla"
        }
    ]
}

This is what I tried:

results = results.search.push({
      "query" : opts.query
});
results = results.concat(links);

Error raised: Cannot call method 'push' of undefined

@alexbeletsky

Copy link
Copy Markdown
Author

@olimart

olimart commented Mar 26, 2015

Copy link
Copy Markdown

Thanks a lot. All good now.

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