restQiitaAPI.js 1.7 KB

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