Tighten up request logic

This commit is contained in:
Greg Shuflin 2021-09-12 22:55:46 -07:00
parent bb80900eb0
commit 4593473b33

View File

@ -36,9 +36,20 @@ const renderConlang = (conlang: Conlang): string => {
}
};
function makeRequest(queryString, jsonHandler) {
const effectiveUrl = `${backendUrl}/${queryString}`;
fetch(`${effectiveUrl}`)
function buildRequest(searchTerm: string, conlang: Conlang, direction: SearchDirection, jsonHandler: (json: Object) => void) {
const specForConlang = {
[Conlang.Saimiar]: 'sai',
[Conlang.Juteyuji]: 'sai',
[Conlang.Tukvaysi]: 'tuk',
[Conlang.Elesu]: 'elesu',
};
const conlangDb = conlang.toString();
const field = direction === SearchDirection.ToConlang ? 'eng' : specForConlang[conlang];
const query = `${conlangDb}?${field}=like.*${searchTerm}*`;
const effectiveUri = `${backendUrl}/${query}`;
fetch(`${effectiveUri}`)
.then((resp) => resp.json())
.then((json) => {
jsonHandler(json);
@ -154,53 +165,32 @@ const App = (_props) => {
const searchConlang = (_evt) => {
const searchTerm = searchBoxInput;
if (conlang === Conlang.Saimiar) {
searchSaimiar(searchTerm);
} else if (conlang === Conlang.Juteyuji) {
searchJuteyuji(searchTerm);
if (searchTerm === '') {
setSearchResults(null);
setSearchTerm(null);
setDirection(null);
return;
}
if (conlang === Conlang.Saimiar || conlang === Conlang.Juteyuji) {
buildRequest(searchTerm, conlang, SearchDirection.ToEnglish, (json) => {
setSearchResults(json);
setSearchTerm(searchTerm);
setDirection(SearchDirection.ToEnglish);
});
} else {
console.error(`Conlang ${conlang} not supported`);
}
};
const searchSaimiar = (searchTerm: string) => {
const request = `saimiar?sai=like.*${searchTerm}*`;
if (searchTerm === '') {
setSearchResults(null);
setSearchTerm(null);
setDirection(null);
} else {
makeRequest(request, (json) => {
setSearchResults(json);
setSearchTerm(searchTerm);
setDirection(SearchDirection.ToEnglish);
});
}
};
const searchJuteyuji = (searchTerm: string) => {
const request = `juteyuji?jut=like.*${searchTerm}*`;
if (searchTerm === '') {
setSearchResults(null);
setSearchTerm(null);
setDirection(null);
} else {
makeRequest(request, (json) => {
setSearchResults(json);
setSearchTerm(searchTerm);
setDirection(SearchDirection.ToEnglish);
});
}
};
const searchEng = (_evt) => {
const searchTerm = searchBoxInput;
const request = `${conlang}?eng=like.*${searchTerm}*`;
if (searchTerm === '') {
setSearchResults(null);
setSearchTerm(null);
setDirection(null);
} else {
makeRequest(request, (json) => {
buildRequest(searchTerm, conlang, SearchDirection.ToConlang, (json) => {
setSearchResults(json);
setSearchTerm(searchTerm);
setDirection(SearchDirection.ToConlang);