index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const got = require('got');
  3. const isPlainObj = require('is-plain-obj');
  4. function ghGot(path, opts) {
  5. if (typeof path !== 'string') {
  6. return Promise.reject(new TypeError(`Expected \`path\` to be a string, got ${typeof path}`));
  7. }
  8. const env = process.env;
  9. opts = Object.assign({
  10. json: true,
  11. token: env.GITHUB_TOKEN,
  12. endpoint: env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : 'https://api.github.com/'
  13. }, opts);
  14. opts.headers = Object.assign({
  15. accept: 'application/vnd.github.v3+json',
  16. 'user-agent': 'https://github.com/sindresorhus/gh-got'
  17. }, opts.headers);
  18. if (opts.token) {
  19. opts.headers.authorization = `token ${opts.token}`;
  20. }
  21. // https://developer.github.com/v3/#http-verbs
  22. if (opts.method && opts.method.toLowerCase() === 'put' && !opts.body) {
  23. opts.headers['content-length'] = 0;
  24. }
  25. const url = /^https?/.test(path) ? path : opts.endpoint + path;
  26. if (opts.stream) {
  27. return got.stream(url, opts);
  28. }
  29. return got(url, opts).catch(err => {
  30. if (err.response && isPlainObj(err.response.body)) {
  31. err.name = 'GitHubError';
  32. err.message = `${err.response.body.message} (${err.statusCode})`;
  33. }
  34. throw err;
  35. });
  36. }
  37. const helpers = [
  38. 'get',
  39. 'post',
  40. 'put',
  41. 'patch',
  42. 'head',
  43. 'delete'
  44. ];
  45. ghGot.stream = (url, opts) => ghGot(url, Object.assign({}, opts, {
  46. json: false,
  47. stream: true
  48. }));
  49. for (const x of helpers) {
  50. const method = x.toUpperCase();
  51. ghGot[x] = (url, opts) => ghGot(url, Object.assign({}, opts, {method}));
  52. ghGot.stream[x] = (url, opts) => ghGot.stream(url, Object.assign({}, opts, {method}));
  53. }
  54. module.exports = ghGot;