-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c2515fd
commit 7abfa56
Showing
1 changed file
with
8 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,48 +1,18 @@ | ||
var findInBatches = require('find-in-batches') | ||
var request = require('request') | ||
var cheerio = require('cheerio') | ||
|
||
exports.search = function (query, options, callback) { | ||
if (arguments.length === 2) { | ||
callback = options | ||
options = {} | ||
options = {limit: 20} | ||
} | ||
|
||
query = (query || '').trim() | ||
if (!query) return callback(null, []) | ||
|
||
var opts = { batchSize: 20, maximum: 20 } | ||
if (options.limit) opts.maximum = options.limit | ||
|
||
var modules = [] | ||
findInBatches.each(opts, function find (options, callback) { | ||
search(query, options, callback) | ||
}, function each (m, done) { | ||
modules.push(m) | ||
done() | ||
}, function (err) { | ||
request({ | ||
method: 'get', | ||
url: 'https://www.npmjs.com/search/suggestions?q=' + query + '&size=' + options.limit || 20, | ||
headers: {'Content-Type': 'application/json'}, | ||
json: true | ||
}, function (err, res, body) { | ||
if (err) return callback(err) | ||
callback(null, modules) | ||
callback(null, body) | ||
}) | ||
} | ||
|
||
function search (query, options, callback) { | ||
var page = options.page - 1 || 0 | ||
return request({ | ||
method: 'get', | ||
url: 'https://www.npmjs.com/search?page=' + page + '&q=' + query | ||
}, function(err, res, body) { | ||
if (err) return callback(err) | ||
var $ = cheerio.load(body) | ||
var modules = [] | ||
$('.package-list-item__capsule___3_4Eo').each(function() { | ||
modules.push({ | ||
name: $(this).find('.package-list-item__title___sqwj8').text(), | ||
version: $(this).find('.package-list-item__version___1u3fc').text(), | ||
author: $(this).find('.package-list-item__publisherName___3I3K2').text(), | ||
description: $(this).find('.package-list-item__description___1nEpN').text() | ||
}) | ||
}) | ||
callback(null, modules) | ||
}) | ||
} |