restQiitaAPI.js 1.8 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. // const req = https.request(options, (res) => {
  20. // const total = res.headers['total-count'];
  21. // res.on('data', (chunk) => {
  22. // resolve([chunk, total]);
  23. // });
  24. request(options, function(err, res, body) {
  25. if (err) {
  26. return console.error('upload failed:', err);
  27. }
  28. const total = res.headers['total-count'];
  29. resolve([body, total]);
  30. });
  31. });
  32. };
  33. restQiitaAPI.getQiitaUser = function() {
  34. return new Promise((resolve, reject) => {
  35. restAPI('users', options)
  36. .then(function(buf, link){
  37. return JSON.parse(buf.toString());
  38. })
  39. .then(function(user) {
  40. if(user.length > 0) {
  41. resolve(user);
  42. }
  43. else {
  44. reject('Incorrect team name or access token.');
  45. }
  46. })
  47. .catch(function(err){
  48. reject(err);
  49. })
  50. });
  51. };
  52. restQiitaAPI.getQiitaPages = function(pageNum) {
  53. return new Promise((resolve, reject) => {
  54. restAPI(`items?page=${pageNum}&per_page=100`, options)
  55. .then(function(res){
  56. const page = res[0];
  57. const total = res[1];
  58. resolve([JSON.parse(page.toString()), total]);
  59. })
  60. .catch(function(err){
  61. reject(err);
  62. })
  63. });
  64. };
  65. return restQiitaAPI;
  66. }