Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 18 additions & 32 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,11 @@ let correct: string = "";
//function to fetch all categories from the API
async function getCategories() {
try {
const endpoint = "api_category.php"

let categories = await getFunction(endpoint);
const categories = await getFunction<Categories>("api_category.php");

if ('trivia_categories' in categories) {
categories as Categories;

categories.trivia_categories.forEach((c: Category) => {
let category = document.createElement("option");
const category = document.createElement("option");
category.setAttribute('value', c.id);
category.textContent = c.name;
categoriesList?.appendChild(category);
Expand All @@ -51,21 +47,13 @@ getCategories();
// function for creating the endpoint according to user input
function createEndpoint() {

let amount = (document.getElementById("amount") as Input)?.value;
// What happens if the elements are not found?
const amount = (document.getElementById("amount") as Input)?.value;
let category = categoriesList?.value;
let difficulty = (document.getElementById("difficulty") as Options)?.value;

if (category === "any") {
category = "";
} else {
category = `&category=${category}`;
}

if (difficulty === "any") {
difficulty = "";
} else {
difficulty = `&difficulty=${difficulty}`;
}
category = category === "any" ? "" : `&category=${category}`;
difficulty = difficulty === "any" ? "" : `&difficulty=${difficulty}`;

return `api.php?amount=${amount}${category}${difficulty}&type=multiple`;
}
Expand All @@ -77,13 +65,12 @@ function generateQuiz() {
quizFilterForm?.addEventListener("submit", async (e) => {
e.preventDefault();

let endpoint = createEndpoint();
const endpoint = createEndpoint();

// function for fetching the data
try {
const questions = await getFunction(endpoint);
if ('results' in questions) {
questions as Data;
const questions = await getFunction<Data>(endpoint);
if (questions.results) {
allQuestions = questions.results;

// set item to local storage
Expand Down Expand Up @@ -151,18 +138,16 @@ function checkIfSelected(variable: Array<Question> | "", func1: (variable: Array

if (checked) {
//Test if something was checked
const alert = document.getElementById("alert");
if (alert) {
alert.remove();
}
document.getElementById("alert")?.remove();

//save answers to localStorage
if (checked?.parentNode?.textContent) {
selectedAnswers.push(checked.parentNode.textContent.trim());
}

encryptData("answers", selectedAnswers)
encryptData("answers", selectedAnswers);

// Bad name
func1(variable);

} else {
Expand Down Expand Up @@ -200,20 +185,21 @@ function checkResult() {
let rightAns = 0;

// get data from localStorage
// Use Generic Type <T>
let questionsCorrectAnswers = decryptQuestions("questions-list");
questionsCorrectAnswers.forEach((q) => {
let question = {
return {
title: HTMLDecode(q.question),
correctAnswer: HTMLDecode(q.correct_answer)
}
return question;
};
});
let answered = decryptAnswers("answers");

const answered = decryptAnswers("answers");

// compare data
questionsCorrectAnswers as QCorrectAns[];
questionsCorrectAnswers.forEach((a: QCorrectAns) => {
if (answered.includes(a.correct_answer)) {
if (answered.indexOf(a.correct_answer) > -1) {
rightAns++;
}
});
Expand Down
5 changes: 3 additions & 2 deletions src/utils/dataEncryption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ export function encryptData(name: string, data: Question[] | string[]) {
localStorage.setItem(name, encrypted);
}

//1 -> decryptQuestions and decryptAnswers can be the one function
export function decryptQuestions(name: string): QCorrectAns[] {
const encrypted = localStorage.getItem(name);
if (typeof encrypted != 'string') {
throw Error('Data type is null.')
throw Error('Data type is null.');
}
const data = CryptoJS.AES.decrypt(encrypted, SECRET_KEY).toString(CryptoJS.enc.Utf8);
const decrypted: QCorrectAns[] = JSON.parse(data);
Expand All @@ -21,7 +22,7 @@ export function decryptQuestions(name: string): QCorrectAns[] {
export function decryptAnswers(name: string): string[] {
const encrypted = localStorage.getItem(name);
if (typeof encrypted != 'string') {
throw Error('Data type is null.')
throw Error('Data type is null.');
}
const data = CryptoJS.AES.decrypt(encrypted, SECRET_KEY).toString(CryptoJS.enc.Utf8);
const decrypted: string[] = JSON.parse(data);
Expand Down
17 changes: 9 additions & 8 deletions src/utils/universalModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,22 @@ const createHeadersFn = (method: string, data: object | '') => {
}

return headers;
}
};

// should have a catch, I dont like await
// Function to perform a fetch request using the specified endpoint and headers
const fetchFn = (endpoint: Endpoint, headers: Headers) => {
const fetchFn = <T>(endpoint: Endpoint, headers: Headers) => {
return fetch(url(endpoint), headers)
.then(response => response.json())
.then((data: Data | Categories) => data);
// .catch((error: string) => console.error('Error fetching data:', error));
}
.then((data: T) => data);
// .catch((error: string) => console.error('Error fetching data:', error));
};

// Function for making a GET request
export const getFunction = (endpoint: Endpoint) => {
export const getFunction = <T>(endpoint: Endpoint) => {
const headers = createHeadersFn('GET', '');
return fetchFn(endpoint, headers);
}
return fetchFn<T>(endpoint, headers);
};

// // Function for making a POST request
// export const postFunction = (endpoint: Endpoint, body: object) => {
Expand Down
16 changes: 7 additions & 9 deletions src/utils/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@ import { BlobWriter, TextReader, ZipWriter } from "@zip.js/zip.js";

onmessage = async (e) => {
const { feedback } = e.data;
if (typeof feedback != 'string') {
// Should be !==, not !=
if (typeof feedback != 'string')
return;
} else {
feedback.replace(/<br\/>/g, '\n');

const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
await zipWriter.add("QuizResult.txt", new TextReader(feedback));
const blob = await zipWriter.close();
postMessage(blob)
};

feedback.replace(/<br\/>/g, '\n');

const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
await zipWriter.add("QuizResult.txt", new TextReader(feedback));
const blob = await zipWriter.close();
postMessage(blob);
};