restQiitaAPI.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. // Qiita API v2 documant https://qiita.com/api/v2/docs
  3. module.exports = function(Team, Token) {
  4. var restQiitaAPI = {};
  5. const request = require('request');
  6. const team = Team;
  7. const token = Token;
  8. var options = {
  9. method: 'GET',
  10. headers: {
  11. 'Content-Type': 'application/json',
  12. 'authorization': `Bearer ${token}`
  13. }
  14. };
  15. function restAPI(path, team, options) {
  16. return new Promise((resolve, reject) => {
  17. options.url = `https://${team}.qiita.com/api/v2/${path}`;
  18. request(options, function(err, res, body) {
  19. if (err) {
  20. return console.error('upload failed:', err);
  21. }
  22. const total = res.headers['total-count'];
  23. resolve([body, total]);
  24. });
  25. });
  26. };
  27. restQiitaAPI.getQiitaUser = function() {
  28. return new Promise((resolve, reject) => {
  29. restAPI('users', team, options)
  30. .then(function(res){
  31. return JSON.parse(res[0].toString());
  32. })
  33. .then(function(user) {
  34. if(user.length > 0) {
  35. resolve(user);
  36. }
  37. else {
  38. reject('Incorrect team name or access token.');
  39. }
  40. })
  41. .catch(function(err){
  42. reject(err);
  43. })
  44. });
  45. };
  46. restQiitaAPI.getQiitaPages = function(pageNum) {
  47. return new Promise((resolve, reject) => {
  48. restAPI(`items?page=${pageNum}&per_page=100`, team, options)
  49. .then(function(res) {
  50. const pages = JSON.parse(res[0].toString());
  51. const total = res[1];
  52. if(pages.length > 0) {
  53. resolve([pages, total]);
  54. }
  55. else {
  56. reject('page not find.');
  57. }
  58. })
  59. .catch(function(err){
  60. reject(err);
  61. })
  62. });
  63. };
  64. return restQiitaAPI;
  65. }