rest-qiita-API.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const debug = require('debug')('growi:service:GlobalNotification');
  2. function getAxios(team, token) {
  3. return require('axios').create({
  4. baseURL: `https://${team}.qiita.com/api/v2`,
  5. headers: {
  6. 'Content-Type': 'application/json',
  7. 'X-Requested-With': 'XMLHttpRequest',
  8. 'authorization': `Bearer ${token}`
  9. },
  10. responseType: 'json'
  11. });
  12. }
  13. /**
  14. * the service class of restQiitaAPI
  15. * Qiita API v2 documant https://qiita.com/api/v2/docs
  16. */
  17. class RestQiitaAPIService {
  18. constructor(crowi) {
  19. this.crowi = crowi;
  20. this.config = crowi.getConfig();
  21. this.team = this.config.crowi['importer:qiita:team_name'];
  22. this.token = this.config.crowi['importer:qiita:access_token'];
  23. this.axios = getAxios(this.team, this.token);
  24. }
  25. /**
  26. * @memberof RestQiitaAPI
  27. * @param {string} team
  28. * @param {string} token
  29. */
  30. async reset() {
  31. this.team = this.config.crowi['importer:qiita:team_name'];
  32. this.token = this.config.crowi['importer:qiita:access_token'];
  33. this.axios = getAxios(this.team, this.token);
  34. }
  35. /**
  36. * get Qiita API
  37. * @memberof RestQiitaAPI
  38. * @param {string} path
  39. */
  40. async restAPI(path) {
  41. return this.axios.get(path)
  42. .then(function(res) {
  43. const data = res.data;
  44. const total = res.headers['total-count'];
  45. return {data, total};
  46. });
  47. }
  48. /**
  49. * get Qiita user
  50. * @memberof RestQiitaAPI
  51. */
  52. async getQiitaUser() {
  53. const res = await this.restAPI('/users');
  54. const user = res.data;
  55. if (user.length > 0) {
  56. return user;
  57. }
  58. }
  59. /**
  60. * get Qiita pages
  61. * @memberof RestQiitaAPI
  62. * @param {string} pageNum
  63. * @param {string} per_page
  64. */
  65. async getQiitaPages(pageNum, per_page) {
  66. const res = await this.restAPI(`/items?page=${pageNum}&per_page=${per_page}`);
  67. const pages = res.data;
  68. const total = res.total;
  69. if (pages.length > 0) {
  70. return {pages, total};
  71. }
  72. }
  73. }
  74. module.exports = RestQiitaAPIService;