API.js 2.5 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.access_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.access_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 ? err : parsedBody.message);
  33. resolve(JSON.parse(body));
  34. });
  35. });
  36. }
  37. static getAccessToken(code) {
  38. const body = {
  39. grant_type: 'authorization_code',
  40. code,
  41. redirect_uri: redirectURI,
  42. client_id: clientId,
  43. client_secret: clientSecret
  44. };
  45. return new Promise((resolve, reject) => {
  46. request.post({url: accessTokenURL, form: body }, (err, response, body) => {
  47. if(err) reject(err);
  48. resolve(JSON.parse(body));
  49. });
  50. });
  51. }
  52. static getAuthorizationUrl() {
  53. const state = Buffer.from(Math.round( Math.random() * Date.now() ).toString() ).toString('hex');
  54. const scope = encodeURIComponent(scopePerms.join(' '));
  55. const url = `${authorizationURL}?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectURI)}&state=${state}&scope=${scope}`;
  56. return url;
  57. }
  58. }
  59. module.exports = API;