forked from sindresorhus/npm-keyword
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (51 loc) · 1.54 KB
/
index.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
57
58
59
60
61
62
63
64
'use strict';
const got = require('got');
const registryUrl = require('registry-url');
const npmConf = require('npm-conf');
function getAuth() {
const conf = npmConf();
const auth = conf.get('_auth');
if (auth) {
return Buffer.from(auth, 'base64').toString('ascii');
}
return auth;
}
async function get(keyword, options) {
if (typeof keyword !== 'string' && !Array.isArray(keyword)) {
throw new TypeError('Keyword must be either a string or an array of strings');
}
if (options.size < 1 || options.size > 250) {
throw new TypeError('Size option must be between 1 and 250');
}
keyword = encodeURIComponent(keyword).replace('%2C', '+');
const url = `${registryUrl()}-/v1/search?text=keywords:${keyword}&size=${options.size}`;
const {body} = await got(url, {json: true, auth: getAuth()});
return body;
}
const npmKeyword = async (keyword, options) => {
options = {
size: 250,
...options
};
const {objects} = await get(keyword, options);
return objects.map(element => ({
name: element.package.name,
description: element.package.description
}));
};
module.exports = npmKeyword;
// TODO: Remove this for the next major release
module.exports.default = npmKeyword;
module.exports.names = async (keyword, options) => {
options = {
size: 250,
...options
};
const {objects} = await get(keyword, options);
return objects.map(element => element.package.name);
};
module.exports.count = async keyword => {
const result = await get(keyword, {size: 1});
require('fs').writeFile('test.txt', JSON.stringify(result));
return result.total;
};