Last active
September 10, 2024 15:32
-
-
Save newhouse/843c444ddefe084ea7f01603627dbcfd to your computer and use it in GitHub Desktop.
Medium API: get number of followers for User
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example of how to get the number of followers for a Medium.com User. | |
* | |
* | |
* Related links: | |
* https://github.com/Medium/medium-api-docs/issues/30#issuecomment-227911763 | |
* https://github.com/Medium/medium-api-docs/issues/73 | |
*/ | |
// LODASH | |
const _ = require('lodash'); | |
// REQUEST LIBRARY | |
const request = require('request-promise'); | |
// WHACKY STUFF THEY PUT IN FRONT OF RESPONSE | |
const JSON_HIJACKING_PREFIX = '])}while(1);</x>'; | |
// BUILD THE URL TO REQUEST FROM | |
function generateMediumProfileUri(username) { | |
return `https://medium.com/@${username}?format=json`; | |
} | |
// HANDLE AND PARSE THE RESPONSE FROM MEDIUM | |
function massageHijackedPreventionResponse(response) { | |
return JSON.parse(response.replace(JSON_HIJACKING_PREFIX, '')); | |
} | |
// EXTRACT THE COUNT FROM THE PROFILE DATA | |
function extractFollowedByCount(profileData) { | |
const userId = _.get(profileData, 'payload.user.userId'); | |
return _.get(profileData, `payload.references.SocialStats.${userId}.usersFollowedByCount`, 0); | |
} | |
// DO THIS THING - RETURNS A PROMISE | |
function getFollwersForUser(username) { | |
const options = { | |
uri: generateMediumProfileUri(username), | |
transform: massageHijackedPreventionResponse | |
}; | |
return request(options) | |
.then(profileData => { | |
let numFollwers = extractFollowedByCount(profileData); | |
return Promise.resolve(numFollwers); | |
}); | |
} | |
let username = 'cwnewhouse'; | |
getFollwersForUser(username) | |
.then(console.log); // 91 or so. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment