restQiitaAPI.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. res.on('data', (chunk) => {
  22. resolve(chunk);
  23. });
  24. });
  25. req.on('error', (e) => {
  26. console.error(`problem with request: ${e.message}`);
  27. });
  28. req.end();
  29. });
  30. };
  31. restQiitaAPI.getQiitaUser = function() {
  32. return new Promise((resolve, reject) => {
  33. restAPI('users', options)
  34. .then(function(buf){
  35. return JSON.parse(buf.toString());
  36. })
  37. .then(function(user) {
  38. if(user.length > 0) {
  39. resolve(user);
  40. }
  41. else {
  42. reject('Unauthorized');
  43. }
  44. })
  45. .catch(function(err){
  46. reject(err);
  47. })
  48. });
  49. };
  50. restQiitaAPI.getQiitaPages = function() {
  51. return new Promise((resolve, reject) => {
  52. restAPI('items', options)
  53. .then(function(page){
  54. resolve(JSON.parse(page.toString()));
  55. })
  56. .catch(function(err){
  57. reject(err);
  58. })
  59. });
  60. };
  61. return restQiitaAPI;
  62. }