API.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const request = require('request');
  3. const { clientId, clientSecret, authorizationURL, redirectURI, accessTokenURL, scopePerms } = require('../config');
  4. class API {
  5. static getLinkedinId(info) {
  6. return new Promise((resolve, reject) => {
  7. const url = 'https://api.linkedin.com/v2/me';
  8. const headers = {
  9. 'Authorization': 'Bearer ' + info.token,
  10. 'cache-control': 'no-cache',
  11. 'X-Restli-Protocol-Version': '2.0.0'
  12. };
  13. request.get({ url: url, headers: headers }, (err, response, body) => {
  14. if(err) {
  15. reject(err);
  16. }
  17. resolve(JSON.parse(body));
  18. });
  19. });
  20. }
  21. static getCompanyFollowers(info) {
  22. return new Promise((resolve, reject) => {
  23. const param = encodeURIComponent(`urn:li:organization:`)+info.companyID+'?edgeType=CompanyFollowedByMember'
  24. const url = `https://api.linkedin.com/v2/networkSizes/${param}`;
  25. const headers = {
  26. 'Authorization': 'Bearer ' + info.token,
  27. 'cache-control': 'no-cache',
  28. 'X-Restli-Protocol-Version': '2.0.0'
  29. };
  30. request.get({ url: url, headers: headers }, (err, response, body) => {
  31. let parsedBody = JSON.parse(body)
  32. if(err || !parsedBody.firstDegreeSize) reject(err);
  33. resolve(JSON.parse(body));
  34. });
  35. });
  36. }
  37. static getAccessToken(req) {
  38. const { code } = req.query;
  39. const body = {
  40. grant_type: 'authorization_code',
  41. code,
  42. redirect_uri: redirectURI,
  43. client_id: clientId,
  44. client_secret: clientSecret
  45. };
  46. return new Promise((resolve, reject) => {
  47. request.post({url: accessTokenURL, form: body }, (err, response, body) => {
  48. if(err) reject(err);
  49. resolve(JSON.parse(body));
  50. });
  51. });
  52. }
  53. static getAuthorizationUrl() {
  54. const state = Buffer.from(Math.round( Math.random() * Date.now() ).toString() ).toString('hex');
  55. const scope = encodeURIComponent(scopePerms.join(' '));
  56. const url = `${authorizationURL}?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectURI)}&state=${state}&scope=${scope}`;
  57. return url;
  58. }
  59. }
  60. module.exports = API;