Skip to content

Commit

Permalink
Merge pull request #118 from Qithub-BOT/refactor/use-fetch-api
Browse files Browse the repository at this point in the history
Fetch API を使う
  • Loading branch information
blhsrwznrghfzpr committed Jan 26, 2020
2 parents bf73f2b + e18ff9c commit d3470dd
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 66 deletions.
56 changes: 30 additions & 26 deletions js/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,42 +166,46 @@ export function registerEventsToCard(element) {
element.addEventListener("dragend", e => handleDragEnd(e), false);
}

/**
* @param {Request | string} input
* @returns {Promise<any>}
*/
export async function fetchJsonAndCheck(input) {
try {
const r = await fetch(input);
if (r.ok) {
return await r.json();
}
throw new Error(`Request failed: ${r.status}`);
} catch (e) {
console.error(e);
return null;
}
}

/**
*
* @param {{instance_full: string, instance: string, toot_ids: string[]}} permalinkObj created by `decodePermalink`
* @param {boolean | undefined} registerEvent
*/
export function showCards(permalinkObj, registerEvent = false) {
export async function showCards(permalinkObj, registerEvent = false) {
const instanceFull = permalinkObj.instance_full;
const tootIds = permalinkObj.toot_ids;
const xhr = new XMLHttpRequest();
const targetDiv = $("cards");
let tootUrl = "";

for (let i = 0; i < tootIds.length; i++) {
tootUrl = instanceFull + "/api/v1/statuses/" + tootIds[i];
xhr.open("GET", tootUrl, false);
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const toot = JSON.parse(xhr.responseText);
const idx = counter.nextIndex();
const tootDiv = createTootDiv(toot);
tootDiv.setAttribute("id", `o_${idx}`);
if (registerEvent === true) {
registerEventsToCard(tootDiv);
}
targetDiv.appendChild(tootDiv);
} else {
console.error(xhr.statusText);
}
const fetchArray = tootIds.map(tootId => fetchJsonAndCheck(`${instanceFull}/api/v1/statuses/${tootId}`));
const toots = await Promise.all(fetchArray);
toots
.filter(toot => toot)
.forEach(toot => {
const tootDiv = createTootDiv(toot);
const idx = counter.nextIndex();
tootDiv.setAttribute("id", `o_${idx}`);
if (registerEvent === true) {
registerEventsToCard(tootDiv);
}
};
xhr.onerror = function() {
console.error(xhr.statusText);
};
xhr.send(null);
}
targetDiv.appendChild(tootDiv);
});

cardList = cardList.concat(tootIds);
genPermalink();
Expand Down
35 changes: 12 additions & 23 deletions js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ function $(id) {
return document.getElementById(id);
}

function showPreview() {
async function showPreview() {
let instanceFull = $("instance").value;
if (instanceFull.trim() === "") {
instanceFull = "https://qiitadon.com";
Expand All @@ -14,24 +14,15 @@ function showPreview() {
const tootId = $("toot-id")
.value.split("/")
.reverse()[0];
const tootUrl = instanceFull + "/api/v1/statuses/" + tootId;
const targetDiv = $("card-preview");
const xhr = new XMLHttpRequest();
xhr.open("GET", tootUrl, true);
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const toot = JSON.parse(xhr.responseText);
targetDiv.innerHTML = impl.createTootDiv(toot).outerHTML;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function() {
console.error(xhr.statusText);
};
xhr.send(null);
if (!tootId) {
return;
}
const toot = await impl.fetchJsonAndCheck(`${instanceFull}/api/v1/statuses/${tootId}`);
if (!toot) {
return;
}
const tootDiv = impl.createTootDiv(toot);
$("card-preview").innerHTML = tootDiv.outerHTML;
}

function addCard() {
Expand Down Expand Up @@ -85,9 +76,7 @@ function copyPermalink() {
function loadPermalink() {
const permalinkObj = impl.decodePermalink(new URL($("load").value).searchParams);
$("instance").value = permalinkObj.instance_full;
impl.showCards(permalinkObj, true);
// impl.showCardsより前に呼び出してはいけない
impl.genPermalink();
impl.showCards(permalinkObj, true).catch(err => console.error(err));
}

function alertUsageNoPermalink() {
Expand All @@ -112,7 +101,7 @@ impl.ready(() => {
loadPermalink();
});
$("showPreview").addEventListener("click", () => {
showPreview();
showPreview().catch(err => console.error(err));
});
$("addCard").addEventListener("click", () => {
addCard();
Expand Down
18 changes: 1 addition & 17 deletions js/p.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
import * as impl from "./common.js";
function $(id) {
return document.getElementById(id);
}

function showPreview() {
impl.showCards(impl.decodePermalink(new URLSearchParams(location.search)));
$("matomain").addEventListener("mouseover", removeAllDraggable, false);
}

function removeAllDraggable() {
const elems = document.querySelectorAll("div.toot");

for (let i = 0; i < elems.length; i++) {
elems[i].removeAttribute("draggable");
}
}
impl.ready(() => {
showPreview();
impl.showCards(impl.decodePermalink(new URLSearchParams(location.search))).catch(err => console.error(err));
});

0 comments on commit d3470dd

Please sign in to comment.