Skip to content

Commit

Permalink
Merge pull request #8 from DiSSCo/SmallImprovementsOnAPI
Browse files Browse the repository at this point in the history
Small improvements on api integration
  • Loading branch information
TomDijkema authored Jun 14, 2024
2 parents e16408e + 3c838ed commit ca57584
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 40 deletions.
9 changes: 7 additions & 2 deletions src/api/taxonomicService/GetTaxonomicService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,18 @@ const GetTaxonomicService = async ({ handle }: { handle?: string }) => {
/* Set Taxonomic Service */
taxonomicService = data.attributes.content as TaxonomicService;

/* Check if Taxonomic Service is published, otherwise throw error */
if (taxonomicService.taxonomicService['cetaf:state'] !== 'published') {
throw (new Error('This Taxonomic Service has not been published yet', { cause: 200 }));
};

/* Set created and modified */
taxonomicService.taxonomicService['ods:created'] = moment(new Date(data.attributes.metadata.createdOn)).format('YYYY-MM-DDTHH:mm:ss.sssZ');
taxonomicService.taxonomicService['dcterms:modified'] = moment(new Date(data.attributes.metadata.modifiedOn)).format('YYYY-MM-DDTHH:mm:ss.sssZ');
} catch (error) {
console.warn(error);
console.error(error);

throw(error);
throw (error);
}
};

Expand Down
25 changes: 21 additions & 4 deletions src/api/taxonomicService/GetTaxonomicServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,26 @@ const GetTaxonomicServices = async ({ pageNumber, pageSize, searchFilters }: { p
/* Destructure search filters into string */
let filters: string = '';

/* Filter for the object type to be a taxonomic service */
filters = filters.concat('/taxonomicService/ods\\:type:taxonomicService');

/* Filter for state to be published */
filters = filters.concat(' AND /taxonomicService/cetaf\\:state:published');

if (!isEmpty(searchFilters)) {
Object.entries(searchFilters).map(([key, value]) => {
/* Get field alias from taxonomic service filters source */
const alias: string | undefined = TaxonomicServiceFilters.taxonomicServiceFilters.find(taxonomicSearchFilter => taxonomicSearchFilter.name === key)?.alias;

filters = filters.concat(` AND ` + `/taxonomicService/${(alias ?? key).replace(':', '\\:')}:` + `${value}`);
if (key === 'language') {
/* Set array search for language */
filters = filters.concat(` AND ` + `/taxonomicService/${(alias ?? key).replace(':', '\\:')}/_:` + `${value}`);
} else if (key === 'query') {
/* Set query to name search */
filters = filters.concat(` AND ` + `/taxonomicService/erp\\:name:` + `${value}*`);
} else {
/* Get field alias from taxonomic service filters source */
filters = filters.concat(` AND ` + `/taxonomicService/${(alias ?? key).replace(':', '\\:')}:` + `${value}`);
}
});
};

Expand All @@ -50,6 +62,11 @@ const GetTaxonomicServices = async ({ pageNumber, pageSize, searchFilters }: { p
/* Get result data from JSON */
const data: CordraResultArray = result.data;

/* Check if there are any results */
if (!data.results.length) {
throw (new Error('No results found', { cause: 200 }));
};

/* Set Taxonomic Services */
data.results.forEach((dataFragment) => {
const taxonomicService = dataFragment.attributes.content as TaxonomicService;
Expand All @@ -67,9 +84,9 @@ const GetTaxonomicServices = async ({ pageNumber, pageSize, searchFilters }: { p
totalRecords: data.size
};
} catch (error) {
console.warn(error);
console.error(error);

throw(error);
throw (error);
};

return {
Expand Down
13 changes: 10 additions & 3 deletions src/app/Hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,17 @@ const usePaginator = ({ Initiate, Method, Handler, ErrorHandler, pageSize, resul
if (pageNumber > 1) {
setErrorMessage('No more records to be found');
} else {
setErrorMessage('Not a single record found, the API servive might be down');
setReturnData({
records: [],
metadata: {
totalRecords: 0
}
});

setErrorMessage('Not a single record found with these criteria');
};

ErrorHandler?.(pageNumber);
ErrorHandler?.(error);
};

setLoading(false);
Expand All @@ -212,7 +219,7 @@ const usePaginator = ({ Initiate, Method, Handler, ErrorHandler, pageSize, resul
/* Initate Function */
useEffect(() => {
Initiate?.();
}, []);
}, [searchParams]);

return {
records: returnData.records ?? [],
Expand Down
7 changes: 6 additions & 1 deletion src/components/general/footer/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@ const Footer = () => {
<Col className="col-lg-auto">
<div className="h-100 d-flex align-items-center fs-5 tc-white fw-lightBold">
<span>
Privacy policy
<a href="https://cetaf.org/privacy/"
target="_blank"
rel="noreferer"
>
Privacy policy
</a>
</span>
<span className="px-2">|</span>
<span>
Expand Down
36 changes: 24 additions & 12 deletions src/components/general/formElements/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* Import Dependencies */
import { useState } from "react";
import { useEffect, useState } from "react";
import Select, { SingleValue } from "react-select";

/* Import Types */
Expand All @@ -18,6 +18,7 @@ interface Props {
value: string,
},
placeholder?: string,
hasDefault?: boolean,
styles?: {
color?: string
},
Expand All @@ -33,7 +34,7 @@ interface Props {
* @param OnChange A global function that triggers when an option is selected, has priority over an action of an option
*/
const Dropdown = (props: Props) => {
const { selectedItem, items, placeholder, styles, OnChange } = props;
const { selectedItem, items, placeholder, hasDefault, styles, OnChange } = props;

/* Base variables */
const [selectItems, setSelectItems] = useState<{ label: string, value: string, action?: Function }[]>(items);
Expand All @@ -44,27 +45,38 @@ const Dropdown = (props: Props) => {
label: placeholder,
value: ""
});
}
};

/**
* Function to check if the chosen option has a value and the default should change to 'Reset filter'
* @param option The selected option from the Select Component
*/
const CheckItems = (option: SingleValue<DropdownItem>) => {
if (option?.value && !selectedItem && !selectItems.find((item) => item.label === 'Reset filter')) {
selectItems[0].label = 'Reset filter';

setSelectItems([...selectItems]);
const CheckItems = (option: SingleValue<DropdownItem> | undefined) => {
if ((option?.value || selectedItem) && !selectItems.find((item) => item.label === 'Reset filter')) {
if (!hasDefault && selectItems[0].label !== placeholder) {
selectItems.unshift({
label: 'Reset filter',
value: ""
});
} else if (!hasDefault) {
selectItems[0].label = 'Reset filter';
}
} else if (!option?.value && selectItems.find((item) => item.label === 'Reset filter')) {
selectItems[0].label = placeholder ?? 'Select an option';

setSelectItems([...selectItems]);
}

setSelectItems([...selectItems]);
}

useEffect(() => {
CheckItems(selectedItem);
}, [selectedItem]);

return (
<Select
value={selectedItem}
<Select value={selectedItem ?? {
label: placeholder ?? 'Select an option',
value: ''
}}
defaultValue={{
label: placeholder ?? 'Select an option',
value: ''
Expand Down
4 changes: 2 additions & 2 deletions src/components/general/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const Header = () => {
>
<Row className="bgc-white py-2 px-2">
<Col lg={{ span: 10, offset: 1 }}>
<Row>
<Row className="align-items-center">
<Col className="col-auto">
<Link to="/">
<img src={CETAFLogo}
Expand All @@ -48,7 +48,7 @@ const Header = () => {
className="d-flex flex-column justify-content-center"
>
<h2 className="w-auto fs-3 fs-lg-2 tc-primary fw-bold">
Marketplace Prototype
Marketplace
</h2>
<h3 className="fs-4 fs-lg-3 tc-grey fw-lightBold">
The Taxonomic Expertise and Services Marketplace
Expand Down
16 changes: 12 additions & 4 deletions src/components/search/Search.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* Import Dependencies */
import classNames from 'classnames';
import { useState } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import { useSearchParams } from 'react-router-dom';

Expand Down Expand Up @@ -33,6 +34,7 @@ const Search = () => {
/* Hooks */
const dispatch = useAppDispatch();
const [searchParams] = useSearchParams();
const [noMoreResults, setNoMoreResults] = useState<boolean>(false);

/* Base variables */
const paginator = usePaginator({
Expand All @@ -43,7 +45,13 @@ const Search = () => {
dispatch(concatToTaxonomicServices(taxonomicServices));
dispatch(setIsApiOnline(true))
},
ErrorHandler: (pageNumber: number) => pageNumber <= 1 && dispatch(setIsApiOnline(false)),
ErrorHandler: (error: Error) => {
if (error.cause === 200) {
setNoMoreResults(true);
} else {
dispatch(setIsApiOnline(false));
};
},
pageSize: 12,
resultKey: 'taxonomicServices',
allowSearchParams: true
Expand All @@ -65,7 +73,7 @@ const Search = () => {
});

const loadMoreBlockClass = classNames({
'h-100': !paginator.loading && paginator.errorMessage,
'flex-grow-1': !paginator.loading && paginator.errorMessage,
'mb-4': !paginator.errorMessage
});

Expand Down Expand Up @@ -100,7 +108,7 @@ const Search = () => {
</Row>
{/* Search Results body */}
<Row className={`${searchResultsClassScrollBlock} flex-grow-1 mt-4`}>
<Col>
<Col className="h-100 d-flex flex-column">
{/* Search Result blocks */}
<Row className={searchResultsClass}>
<Col>
Expand All @@ -125,7 +133,7 @@ const Search = () => {
Load more
</Button>
: <>
{(!paginator.errorMessage && paginator.totalRecords > 0) ?
{(!noMoreResults && paginator.totalRecords > 0) ?
<Spinner />
: <Row className="h-100 align-items-center">
<Col>
Expand Down
6 changes: 4 additions & 2 deletions src/components/search/components/Filter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Dropdown, DatePicker } from 'components/general/FormComponents';
type Props = {
filter: FilterType,
currentValue?: string | number | boolean | Date,
hasDefault?: boolean,
SetFilterValue: Function,
SubmitForm: Function
};
Expand All @@ -24,7 +25,7 @@ type Props = {
* @param SubmitForm Function to submit the form
*/
const Filter = (props: Props) => {
const { filter, currentValue, SetFilterValue, SubmitForm } = props;
const { filter, currentValue, hasDefault, SetFilterValue, SubmitForm } = props;

switch (filter.type) {
case 'select':
Expand All @@ -37,14 +38,15 @@ const Filter = (props: Props) => {
value: `${currentValue}`
} : undefined}
placeholder={MakeReadableString(filter.name)}
hasDefault={hasDefault}
styles={{
color: '#FF8E3E'
}}
OnChange={(item: DropdownItem) => {
SetFilterValue(item.value);
SubmitForm();
}}
/>
/>;
}
return <> </>;
case 'date':
Expand Down
8 changes: 6 additions & 2 deletions src/components/search/components/FiltersBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const FiltersBar = (props: Props) => {
query: searchParams.get('query') ?? '',
...initialValues
}}
enableReinitialize={true}
onSubmit={async (values) => {
/* Filter handling is done in the individual components */
await new Promise((resolve) => setTimeout(resolve, 100));
Expand All @@ -71,7 +72,8 @@ const FiltersBar = (props: Props) => {
ToggleFilters?.();
}}
>
{({ values, setFieldValue, submitForm }) => (
{({ values, setFieldValue, submitForm }) => {
return (
<Form>
<Row>
{/* Search Bar */}
Expand All @@ -96,6 +98,7 @@ const FiltersBar = (props: Props) => {
>
<Filter filter={filter}
currentValue={values[filter.name as keyof typeof values]}
hasDefault={!!filters.find(originalFilter => originalFilter.name === filter.name)?.default}
SetFilterValue={(value: string | number | boolean) => setFieldValue(filter.name, value)}
SubmitForm={() => submitForm()}
/>
Expand All @@ -105,7 +108,8 @@ const FiltersBar = (props: Props) => {
</Col>
</Row>
</Form>
)}
)
}}
</Formik>
);
}
Expand Down
Loading

0 comments on commit ca57584

Please sign in to comment.