rest-qiita-API.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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.configManager = crowi.configManager;
  20. this.team = this.configManager.getConfig('crowi', 'importer:qiita:team_name');
  21. this.token = this.configManager.getConfig('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.configManager.getConfig('crowi', 'importer:qiita:team_name');
  31. this.token = this.configManager.getConfig('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((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} perPage
  63. */
  64. async getQiitaPages(pageNum, perPage) {
  65. const res = await this.restAPI(`/items?page=${pageNum}&per_page=${perPage}`);
  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;