restQiitaAPI.js 1.7 KB

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