extracted api logic to service script

This commit is contained in:
Lauchmelder 2022-03-20 01:04:00 +01:00
parent e0e764ccc2
commit e9f95c1001
No known key found for this signature in database
GPG key ID: C2403C69D78F011D
2 changed files with 22 additions and 68 deletions

View file

@ -11,9 +11,13 @@
Download Data
</button>
<button id="print">
Print Data
</button>
<p id="loading">
</p>
<p>
Using WaniKani Level <span id="level"></span>
</p>
<script src="popup.js"></script>
</body>

View file

@ -1,74 +1,24 @@
const getStorageData = key =>
new Promise((resolve, reject) =>
chrome.storage.local.get(key, result =>
chrome.runtime.lastError
? reject(Error(chrome.runtime.lastError.message))
: resolve(result)
)
)
const query = async (token, url) => {
const requestHeaders = new Headers()
requestHeaders.append("Authorization", "Bearer " + token)
const endpoint = new Request(
url,
{
method: "GET",
headers: requestHeaders
}
)
var result = await fetch(endpoint)
return result.json()
}
const submitButton = document.getElementById("submit-token");
const submitButton = document.getElementById("submit-token")
const inputField = document.getElementById("token");
submitButton.addEventListener( "click", () => {
chrome.storage.local.set({"token": inputField.value})
})
const downloadButton = document.getElementById("download");
const downloadButton = document.getElementById("download")
downloadButton.addEventListener("click", async () => {
const userData = await getStorageData("token")
var url = "https://api.wanikani.com/v2/user"
var response = await query(userData.token, url)
var level = response.data.level
var levelArray = []
for(var i = 1; i < level; i++)
levelArray.push(i)
var loadingText = document.getElementById("loading")
loadingText.innerHTML = "Loading..."
var levelURLString = levelArray.join(",")
chrome.runtime.sendMessage("", {type: "sync"}, response => {
if(response.success)
loadingText.innerHTML = "Done!"
else
loadingText.innerHTML = response.error
})
})
var url = "https://api.wanikani.com/v2/subjects?types=vocabulary&levels=" + levelURLString
var vocabulary = []
do
{
var response = await query(userData.token, url)
for(let i in response.data)
vocabulary.push(response.data[i].data.characters)
url = response.pages.next_url
} while(url !== null)
var url = "https://api.wanikani.com/v2/subjects?types=kanji&levels=" + levelURLString
var kanji = []
do
{
var response = await query(userData.token, url)
for(let i in response.data)
kanji.push(response.data[i].data.characters)
url = response.pages.next_url
} while(url !== null)
chrome.storage.local.set({
"vocabulary": vocabulary,
"kanji": kanji
})
console.log("Downloaded data!")
})
chrome.storage.local.get("level", (data) => {
const levelSpan = document.getElementById("level")
levelSpan.innerHTML = data.level
})