Refactor code to reduce requests

This commit is contained in:
Gabriel Augendre 2023-01-01 02:55:32 +01:00
parent 4c25b59fcd
commit b67b057d48
2 changed files with 26 additions and 23 deletions

View file

@ -9,7 +9,19 @@ function loadAvailableFiles() {
console.log("Available files..."); console.log("Available files...");
fetch("/available-files") fetch("/available-files")
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(handleAvailableFiles);
}
function selectFile(name) {
console.log("Select file");
const body = new FormData();
body.set("fileName", name);
fetch("/select-file", {method: "POST", body: body})
.then(response => response.json())
.then(handleAvailableFiles);
}
function handleAvailableFiles(data) {
console.log("data", data); console.log("data", data);
let dom = ""; let dom = "";
data.files.forEach(element => { data.files.forEach(element => {
@ -21,15 +33,6 @@ function loadAvailableFiles() {
} }
}); });
document.getElementById("available-files").innerHTML = dom; document.getElementById("available-files").innerHTML = dom;
});
}
function selectFile(name) {
console.log("Select file");
const body = new FormData();
body.set("fileName", name);
fetch("/select-file", {method: "POST", body: body})
.then(res => loadAvailableFiles());
} }
(() => { (() => {

View file

@ -40,9 +40,8 @@ void onAvailableFiles(AsyncWebServerRequest *request)
File file = music.openNextFile(); File file = music.openNextFile();
while (file) while (file)
{ {
Serial.print("File: ");
String fileName = file.name(); String fileName = file.name();
Serial.println(fileName); if (!fileName.startsWith("."))
files.add(fileName); files.add(fileName);
file.close(); file.close();
file = music.openNextFile(); file = music.openNextFile();
@ -61,7 +60,7 @@ void onSelectFile(AsyncWebServerRequest *request)
Serial.print(selectedFile); Serial.print(selectedFile);
} }
Serial.println(); Serial.println();
request->send(200); onAvailableFiles(request);
} }
void setup() void setup()
@ -79,12 +78,13 @@ void setup()
} }
// List existing files // List existing files
File root = SPIFFS.open("/"); File root = SPIFFS.open("/music");
File file = root.openNextFile(); File file = root.openNextFile();
while (file) while (file)
{ {
Serial.print("File: "); String fileName = file.name();
Serial.println(file.path()); if (selectedFile == "" && !fileName.startsWith("."))
selectedFile = fileName;
file.close(); file.close();
file = root.openNextFile(); file = root.openNextFile();
} }