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
35 changes: 26 additions & 9 deletions www/activities/foodlist/js/usda.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,18 +212,35 @@ app.USDA = {
let url = "https://api.nal.usda.gov/fdc/v1/foods/search?api_key=" + encodeURIComponent(key) + "&query=cheese";

let response = await app.Utils.timeoutFetch(url).catch((err) => {
resolve(false);
resolve({
valid: false,
reason: "network"
});
});

if (response && response.ok) {
let data = await response.json();
if (data.error && data.error.code == "API_KEY_INVALID")
resolve(false);
else
resolve(true);
if (response) {
if (response.ok) {
resolve({
valid: true
});
} else {
let data = await response.json().catch((err) => undefined);
let code = data && data.error && data.error.code;

let reason;
if (code == "OVER_RATE_LIMIT" || response.status == 429)
reason = "rate-limit";
else if (code == "API_KEY_INVALID" || response.status == 403)
reason = "invalid-key";
else
reason = "network";

resolve({
valid: false,
reason: reason
});
}
}

resolve(false);
});
}
};
10 changes: 9 additions & 1 deletion www/activities/settings/js/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,11 +346,19 @@ app.Settings = {
saveUSDAKey: async function(key) {
let screen = document.querySelector(".usda-login");
if (app.Utils.isInternetConnected()) {
if (key == "" || await app.USDA.testApiKey(key)) {
let result = key == "" ? { valid: true } : await app.USDA.testApiKey(key);

if (result.valid) {
this.put("integration", "usda-key", key);
app.f7.loginScreen.close(screen);
let msg = app.strings.settings.integration["login-success"] || "Login Successful";
app.Utils.toast(msg);
} else if (result.reason == "rate-limit") {
let msg = app.strings.settings.integration["usda-rate-limited"] || "USDA rate limit reached, try again later";
app.Utils.toast(msg);
} else if (result.reason == "network") {
let msg = app.strings.settings.integration["usda-key-check-failed"] || "Couldn't verify key, check your connection and try again";
app.Utils.toast(msg);
} else {
let msg = app.strings.settings.integration["invalid-api-key"] || "API Key Invalid";
app.Utils.toast(msg);
Expand Down
2 changes: 2 additions & 0 deletions www/assets/locales/locale-en.json
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,8 @@
"save": "Save",
"invalid-credentials": "Invalid Credentials",
"invalid-api-key": "API Key Invalid",
"usda-rate-limited": "USDA rate limit reached, try again later",
"usda-key-check-failed": "Couldn't verify key, check your connection and try again",
"export-success": "Database Exported",
"export-fail": "Export Failed",
"import-fail": "Import Failed",
Expand Down