githubClient.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
  2. const baseURL = 'https://api.github.com/repos/grafana/grafana';
  3. // Encapsulates the creation of a client for the Github API
  4. //
  5. // Two key things:
  6. // 1. You can specify whenever you want the credentials to be required or not when imported.
  7. // 2. If the the credentials are available as part of the environment, even if
  8. // they're not required - the library will use them. This allows us to overcome
  9. // any API rate limiting imposed without authentication.
  10. class GithubClient {
  11. client: AxiosInstance;
  12. constructor(required = false) {
  13. const username = process.env.GITHUB_USERNAME;
  14. const token = process.env.GITHUB_ACCESS_TOKEN;
  15. const clientConfig: AxiosRequestConfig = {
  16. baseURL: baseURL,
  17. timeout: 10000,
  18. };
  19. if (required && !username && !token) {
  20. throw new Error('operation needs a GITHUB_USERNAME and GITHUB_ACCESS_TOKEN environment variables');
  21. }
  22. if (username && token) {
  23. clientConfig.auth = { username: username, password: token };
  24. }
  25. this.client = this.createClient(clientConfig);
  26. }
  27. private createClient(clientConfig: AxiosRequestConfig) {
  28. return axios.create(clientConfig);
  29. }
  30. }
  31. export default GithubClient;