Last active
July 30, 2021 20:35
-
-
Save rmkubik/db54a3ace509fe4e0ffec6f008e8588d to your computer and use it in GitHub Desktop.
TQ - URL Parsing Validator
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
// parsing a URL for a GitHub repository link like so: | |
// https://github.com/twilioquest/twilioquest-extension-template | |
module.exports = async function (helper) { | |
const { userUrl } = helper.validationFields; | |
let parsedUserUrl; | |
try { | |
parsedUserUrl = new URL(userUrl); | |
} catch (err) { | |
return helper.fail(` | |
"${userUrl}" is not a valid URL. | |
`); | |
} | |
if (!parsedUserUrl.hostname.toLowerCase().includes("github.com")) { | |
return helper.fail(` | |
"${userUrl}" is not a Github URL. | |
`); | |
} | |
const partsOfPathName = parsedUserUrl.pathname.toLowerCase().split("/"); | |
// const [, user, repository] = partsOfPathname; | |
const user = partsOfPathName[1]; | |
const repository = partsOfPathName[2] | |
if (user !== "twilioquest") { | |
return helper.fail(` | |
"${userUrl}" is not owned by TwilioQuest! | |
`); | |
} | |
if (!repository) { | |
return helper.fail(` | |
"${userUrl}" does not contain a repository link! | |
`); | |
} | |
let avatar_url; | |
try { | |
const response = await fetch( | |
`https://api.github.com/users/${user}` | |
).then((response) => response.json()); | |
avatar_url = response.avatar_url; | |
} catch (err) { | |
console.log(`Failed to request profile image for "${user}"`); | |
} | |
return helper.success(` | |
We found the repository "${repository}" owned by "${user}"! | |
<img src="${avatar_url}" alt="User's profile image" /> | |
`); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment