rest-qiita-API.js 1.9 KB

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