-
Notifications
You must be signed in to change notification settings - Fork 0
/
pypi.js
56 lines (47 loc) · 1.31 KB
/
pypi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const xmlrpc = require('xmlrpc')
const fuzzyfind = require('fuzzyfind')
const fetch = require('node-fetch')
const DEFAULT_URL = 'https://pypi.python.org/pypi'
class PyPi {
constructor () {
this.client = xmlrpc.createSecureClient(DEFAULT_URL)
}
getPackages () {
return new Promise((resolve) => {
if (this.cache) return resolve()
this.client.methodCall('list_packages', [], (err, value) => {
this.cache = value
resolve()
})
}).then(() => {
return this.cache
})
}
search (query) {
const packageResults = []
const readResponse = (response) => {
return response.json()
}
const addPkgResult = (json) => {
packageResults.push({
pkg: json['info']['name'],
info: json['info']['summary']
})
}
return this.getPackages().then((results) => {
let promise = Promise.resolve()
fuzzyfind(query, results).slice(0, 5).forEach((pkg) => {
promise = promise.then(() => {
let pkgDetails = `https://pypi.python.org/pypi/${pkg}/json`
return fetch(pkgDetails).then(readResponse).then(addPkgResult)
})
})
return promise.then((response) => {
return packageResults
}).catch((e) => {
console.error('fail', e)
})
})
}
}
module.exports = PyPi