Skip to content

Commit

Permalink
Refactor parser function into callback in ListResources [#870]
Browse files Browse the repository at this point in the history
Convert the two existing uses into the callback form.

This does not add any new functionality, it only re-arranges
implementation of existing functionality.
  • Loading branch information
genehack committed Jun 7, 2024
1 parent 5f75819 commit a1bbba7
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 14 deletions.
19 changes: 14 additions & 5 deletions static-site/src/components/ListResources/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import { ErrorContainer } from "../../pages/404";
import { TooltipWrapper } from "./IndividualResource";
import {ResourceModal, SetModalResourceContext} from "./Modal";
import { Showcase, useShowcaseCards} from "./Showcase";
import { Card, FilterOption, Group, GroupDisplayNames, QuickLink, Resource } from './types';
import { Card, FilterOption, Group, GroupDisplayNames, QuickLink, Resource, ResourceListingInfo } from './types';
import { HugeSpacer } from "../../layouts/generalComponents";

interface ListResourcesProps extends ListResourcesResponsiveProps {
elWidth: number
Expand All @@ -37,8 +38,15 @@ function ListResources({
defaultGroupLinks=false,
groupDisplayNames,
showcase,
parserCallBackFxn,
}: ListResourcesProps) {
const {groups, dataFetchError} = useDataFetch(sourceId, versioned, defaultGroupLinks, groupDisplayNames);
const {groups, dataFetchError} = useDataFetch(
sourceId,
versioned,
defaultGroupLinks,
groupDisplayNames,
parserCallBackFxn,
);
const showcaseCards = useShowcaseCards(showcase, groups);
const [selectedFilterOptions, setSelectedFilterOptions] = useState<readonly FilterOption[]>([]);
const [sortMethod, changeSortMethod] = useState("alphabetical");
Expand All @@ -49,7 +57,7 @@ function ListResources({

if (dataFetchError) {
return (
<ErrorContainer>
<ErrorContainer>
{"Whoops - listing resources isn't working!"}
<br/>
{'Please '}<Link href="/contact" style={{fontWeight: 300}}>get in touch</Link>{" if this keeps happening"}
Expand Down Expand Up @@ -109,6 +117,7 @@ interface ListResourcesResponsiveProps {
defaultGroupLinks: boolean
groupDisplayNames: GroupDisplayNames
showcase: Card[]
parserCallBackFxn: (response: Response) => Promise<ResourceListingInfo>;
}

/**
Expand Down Expand Up @@ -153,7 +162,7 @@ function SortOptions({sortMethod, changeSortMethod}) {
}
return (
<SortContainer>
Sort pathogens by:
Sort pathogens by:
<input id="alphabetical" type="radio" onChange={onChangeValue} value="alphabetical"
checked={"alphabetical"===sortMethod} style={{cursor: "alphabetical"===sortMethod ? 'default' : 'pointer'}}/>
<TooltipWrapper description={'Pathogen groups ordered alphabetically. ' +
Expand Down Expand Up @@ -223,4 +232,4 @@ const SortContainer = styled.div`
margin-left: 20px;
margin-right: 5px;
}
`
`
5 changes: 5 additions & 0 deletions static-site/src/components/ListResources/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ export interface ResourceDisplayName {
default: string
}

export interface ResourceListingInfo {
pathPrefix: string
pathVersions: PathVersions
}

/**
* Mapping from group name -> display name
*/
Expand Down
31 changes: 25 additions & 6 deletions static-site/src/components/ListResources/useDataFetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { Group, GroupDisplayNames, PathVersions, Resource } from './types';
import { Group, GroupDisplayNames, PathVersions, Resource, ResourceListingInfo } from './types';


/**
Expand All @@ -8,25 +8,44 @@ import { Group, GroupDisplayNames, PathVersions, Resource } from './types';
* resources for each, and the available versions (snapshots) for each of those
* resources.
*
* Needs to be provided a callback function that returns the
`pathVersions` and `pathPrefix` values for the fetched datasets.
*
* The current implementation defines `versioned: boolean` for the entire API
* response, however in the future we may shift this to the API response and it
* may vary across the resources returned.
*/
export function useDataFetch(sourceId: string, versioned: boolean, defaultGroupLinks: boolean, groupDisplayNames: GroupDisplayNames) {
export function useDataFetch(
sourceId: string,
versioned: boolean,
defaultGroupLinks: boolean,
groupDisplayNames: GroupDisplayNames,
parserCallBack: (response: Response) => Promise<ResourceListingInfo>,
) : {groups: Group[] | undefined, dataFetchError: boolean | undefined} {
const [groups, setGroups] = useState<Group[]>();
const [dataFetchError, setDataFetchError] = useState<boolean>();
useEffect(() => {
const url = `/list-resources/${sourceId}`;
useEffect((): void => {
let url: string;
// if we're passed a `sourceId` that starts with `charon/`, assume
// we're being asked to use Charon's `getAvailable` endpoint with
// the provided `sourceId` as the prefix. otherwise, use the
// `/list-resources` endpoint to pull that source.
if (sourceId.startsWith("charon/")) {
const subSourceId = sourceId.replace(/^charon\//, "");
url = `/charon/getAvailable?prefix=${subSourceId}`;
} else {
url = `/list-resources/${sourceId}`;
}

async function fetchAndParse() {
async function fetchAndParse(): Promise<void> {
let pathVersions: PathVersions, pathPrefix: string;
try {
const response = await fetch(url, {headers: {accept: "application/json"}});
if (response.status !== 200) {
console.error(`ERROR: fetching data from "${url}" returned status code ${response.status}`);
return setDataFetchError(true);
}
({ pathVersions, pathPrefix } = (await response.json()).dataset[sourceId]);
({ pathVersions, pathPrefix } = await parserCallBack(response));
} catch (err) {
console.error(`Error while fetching data from "${url}"`);
console.error(err);
Expand Down
10 changes: 8 additions & 2 deletions static-site/src/sections/pathogens.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ const abstract = (
</>
);

const sourceId = "core";
const parserCallBackFxn = async (response) => (await response.json()).dataset[sourceId];

class Index extends React.Component {
render() {
return (
Expand All @@ -36,9 +39,12 @@ class Index extends React.Component {
</FlexCenter>

<HugeSpacer/>
<ListResources sourceId="core" resourceType="dataset"

<ListResources sourceId={sourceId} resourceType="dataset"
showcase={coreShowcase}
quickLinks={coreQuickLinks} defaultGroupLinks groupDisplayNames={coreGroupDisplayNames}/>
quickLinks={coreQuickLinks} defaultGroupLinks groupDisplayNames={coreGroupDisplayNames}
parserCallBackFxn={parserCallBackFxn}/>

<HugeSpacer/>
</GenericPage>
);
Expand Down
6 changes: 5 additions & 1 deletion static-site/src/sections/staging-page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const abstract = (
</>
);

const sourceId = "staging";
const parserCallBackFxn = async (response) => (await response.json()).dataset[sourceId];

class Index extends React.Component {
constructor(props) {
super(props);
Expand Down Expand Up @@ -62,7 +65,8 @@ class Index extends React.Component {
</FlexCenter>
<HugeSpacer />

<ListResources sourceId="staging" resourceType="dataset" versioned={false}/>
<ListResources sourceId={sourceId} resourceType="dataset" versioned={false}
parserCallBackFxn={parserCallBackFxn}/>

<HugeSpacer />

Expand Down

0 comments on commit a1bbba7

Please sign in to comment.