Skip to content

Instantly share code, notes, and snippets.

@rmkubik
Last active July 30, 2021 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmkubik/db54a3ace509fe4e0ffec6f008e8588d to your computer and use it in GitHub Desktop.
Save rmkubik/db54a3ace509fe4e0ffec6f008e8588d to your computer and use it in GitHub Desktop.
TQ - URL Parsing Validator
// 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