rest-qiita-API.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * get Qiita API
  27. * @memberof RestQiitaAPI
  28. * @param {string} path
  29. */
  30. async restAPI(path) {
  31. return this.axios.get(path)
  32. .then(function(res) {
  33. const data = res.data;
  34. const total = res.headers['total-count'];
  35. return {data, total};
  36. })
  37. .catch(function(err) {
  38. return err;
  39. });
  40. };
  41. /**
  42. * get Qiita user
  43. * @memberof RestQiitaAPI
  44. */
  45. async getQiitaUser() {
  46. try {
  47. const res = await this.restAPI('/users');
  48. const user = res.data;
  49. if(user.length > 0) {
  50. return user;
  51. }
  52. } catch (err) {
  53. throw err;
  54. }
  55. };
  56. /**
  57. * get Qiita pages
  58. * @memberof RestQiitaAPI
  59. * @param {string} pageNum
  60. * @param {string} per_page
  61. */
  62. async getQiitaPages(pageNum, per_page) {
  63. try {
  64. const res = await this.restAPI(`/items?page=${pageNum}&per_page=${per_page}`);
  65. const pages = res.data;
  66. const total = res.total;
  67. if(pages.length > 0) {
  68. return {pages, total};
  69. }
  70. } catch (err) {
  71. throw err;
  72. }
  73. };
  74. }
  75. module.exports = RestQiitaAPIService;