|
| 1 | +console.log("index.js: loaded"); |
| 2 | + |
| 3 | +function escapeSpecialChars(str) { |
| 4 | + return str |
| 5 | + .replace(/&/g, "&") |
| 6 | + .replace(/</g, "<") |
| 7 | + .replace(/>/g, ">") |
| 8 | + .replace(/"/g, """) |
| 9 | + .replace(/'/g, "'"); |
| 10 | +} |
| 11 | + |
| 12 | +function escapeHTML(strings, ...values) { |
| 13 | + return strings.reduce((result, str, i) => { |
| 14 | + const value = values[i - 1]; |
| 15 | + if (typeof value === "string") { |
| 16 | + return result + escapeSpecialChars(value) + str; |
| 17 | + } else { |
| 18 | + return result + String(value) + str; |
| 19 | + } |
| 20 | + }) |
| 21 | +} |
| 22 | + |
| 23 | +function createView(userInfo) { |
| 24 | + return escapeHTML` |
| 25 | + <h4>${userInfo.name} (@${userInfo.login})</h4> |
| 26 | + <img src="${userInfo.avatar_url}" alt="${userInfo.login}" height="100"> |
| 27 | + <dl> |
| 28 | + <dt>Location</dt> |
| 29 | + <dd>${userInfo.location}</dd> |
| 30 | +
|
| 31 | + <dt>Repositories</dt> |
| 32 | + <dd>${userInfo.public_repos}</dd> |
| 33 | + </dl> |
| 34 | + `; |
| 35 | +} |
| 36 | + |
| 37 | +function displayView(view) { |
| 38 | + const result = document.getElementById("result"); |
| 39 | + result.innerHTML = view; |
| 40 | +} |
| 41 | + |
| 42 | +function fetchUserInfo(userId) { |
| 43 | + return fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`) |
| 44 | + .then(response => { |
| 45 | + if (!response.ok) { |
| 46 | + return Promise.reject(new Error(`${response.status}: ${response.statusText}`)); |
| 47 | + } else { |
| 48 | + return response.json(); |
| 49 | + } |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +function getUserId() { |
| 54 | + const value = document.getElementById("userId").value; |
| 55 | + return encodeURIComponent(value); |
| 56 | +} |
| 57 | + |
| 58 | +async function main() { |
| 59 | + try { |
| 60 | + const userId = getUserId(); |
| 61 | + const userInfo = await fetchUserInfo(userId); |
| 62 | + const view = createView(userInfo); |
| 63 | + displayView(view); |
| 64 | + } catch (error) { |
| 65 | + console.error(`エラーが発生しました (${error})`); |
| 66 | + } |
| 67 | +} |
0 commit comments