You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.4 KiB
JavaScript
53 lines
1.4 KiB
JavaScript
'use strict';
|
|
|
|
const Promise = require("bluebird");
|
|
const bhttp = require("bhttp");
|
|
const querystring = require("querystring");
|
|
const defaultValue = require("default-value");
|
|
const rfr = require("rfr");
|
|
|
|
const cacheize = rfr("lib/db/cacheize");
|
|
|
|
module.exports = function(autocompleteKey, cache) {
|
|
function createQueryString(query, options) {
|
|
return querystring.stringify({
|
|
autocomplete_key: autocompleteKey,
|
|
_: Date.now(),
|
|
query: query,
|
|
num_results: defaultValue(options.resultCount, 20)
|
|
});
|
|
}
|
|
|
|
function createUrl(query, options) {
|
|
return `https://ac.cnstrc.com/autocomplete/${encodeURIComponent(query)}?${createQueryString(query, options)}`;
|
|
}
|
|
|
|
return cacheize(cache, function doSearch(query, options = {}) {
|
|
return Promise.try(() => {
|
|
if (query.trim() !== "") {
|
|
return Promise.try(() => {
|
|
return bhttp.get(createUrl(query, options));
|
|
}).then((response) => {
|
|
if (response.statusCode === 200) {
|
|
return {
|
|
packages: response.body.sections.packages.map((pkg) => {
|
|
return {
|
|
name: pkg.value,
|
|
description: pkg.data.description
|
|
}
|
|
}),
|
|
suggestions: response.body.sections.standard
|
|
};
|
|
} else {
|
|
throw new Error(`Non-200 status code encountered: ${response.statusCode}`)
|
|
}
|
|
});
|
|
} else {
|
|
return {
|
|
packages: [],
|
|
suggestions: []
|
|
}
|
|
}
|
|
})
|
|
})
|
|
} |