1 | 'use strict';
|
2 | var got = require('got');
|
3 | var querystring = require('querystring');
|
4 |
|
5 | module.exports = function (email, token, cb) {
|
6 | if (typeof email !== 'string' && email.indexOf('@') !== -1) {
|
7 | throw new Error('`email` required');
|
8 | }
|
9 |
|
10 | if (typeof token === 'function') {
|
11 | cb = token;
|
12 | token = null;
|
13 | }
|
14 |
|
15 | var headers = {
|
16 | 'user-agent': 'https://github.com/sindresorhus/github-username'
|
17 | };
|
18 |
|
19 | if (token) {
|
20 | headers['Authorization'] = 'token ' + token;
|
21 | }
|
22 |
|
23 | var qs = querystring.stringify({
|
24 | q: email + ' in:email'
|
25 | });
|
26 |
|
27 | got.get('https://api.github.com/search/users?' + qs, {
|
28 | headers: headers
|
29 | }, function (err, data) {
|
30 | if (err) {
|
31 | cb(err);
|
32 | return;
|
33 | }
|
34 |
|
35 | data = JSON.parse(data);
|
36 |
|
37 | if (data.total_count === 0) {
|
38 | cb(new Error('Couldn\'t find a username for the supplied email'));
|
39 | return;
|
40 | }
|
41 |
|
42 | cb(null, data.items[0].login);
|
43 | });
|
44 | };
|