Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task/des 3047 create custom query hooks #1383

Open
wants to merge 3 commits into
base: feat/recon-portal-react
Choose a base branch
from
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
1 change: 1 addition & 0 deletions client/modules/_hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './workspace';
export * from './datafiles';
export * from './systems';
export * from './notifications';
export * from './reconportal';
3 changes: 3 additions & 0 deletions client/modules/_hooks/src/reconportal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './useGetEvents';
export * from './useGetEventTypes';
export * from './useGetOpenTopo';
30 changes: 30 additions & 0 deletions client/modules/_hooks/src/reconportal/useGetEventTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// src/reconportal/useGetEventTypes.ts
import { useSuspenseQuery, useQueryClient } from '@tanstack/react-query';
import apiClient, { TApiError } from '../apiClient';

export type EventTypeResponse = {
display_name: string;
name: string;
};

async function getEventTypes() {
const res = await apiClient.get<EventTypeResponse[]>('/recon-portal/event-types');
return res.data;
}

export const getEventTypesQuery = () => ({
queryKey: ['reconportal', 'getEventTypes'],
queryFn: getEventTypes,
staleTime: 1000 * 60 * 5, // 5 minute stale time
});

export function useGetEventTypes() {
return useSuspenseQuery(getEventTypesQuery());
}

export const usePrefetchGetEventTypes = () => {
const queryClient = useQueryClient();
queryClient.ensureQueryData(getEventTypesQuery());
};

export default useGetEventTypes;
40 changes: 40 additions & 0 deletions client/modules/_hooks/src/reconportal/useGetEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// src/reconportal/useGetEvents.ts
import { useQuery } from '@tanstack/react-query';
import apiClient, { TApiError } from '../apiClient';

export type Dataset = {
url: string;
title: string;
doi: string;
id: string;
};

export type EventsResponse = {
location_description: string;
location: {
lat: number;
lon: number;
};
event_date: string;
event_type: string;
title: string;
created_date: string;
datasets: Dataset[];
};

async function getEvents() {
const res = await apiClient.get<EventsResponse[]>('/recon-portal/events');
return res.data;
}

export const getEventsQuery = () => ({
queryKey: ['events'],
queryFn: getEvents,
staleTime: 1000 * 60 * 5, // 5 minute stale time
});

export function useGetEvents() {
return useQuery(getEventsQuery());
}

export default useGetEvents;
169 changes: 169 additions & 0 deletions client/modules/_hooks/src/reconportal/useGetOpenTopo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { useQuery } from '@tanstack/react-query';
import apiClient from '../apiClient';
import * as turf from '@turf/turf';
import { Feature, Point, Polygon, MultiPolygon } from 'geojson';

export type OpenTopoFeature = {
type: 'Feature';
properties: {
id: string;
name: string;
productAvailable: string;
dateCreated: string;
temporalCoverage: string;
doiUrl: string;
url: string;
host: string;
keywords: string;
alternateName: string;
};
geometry: {
type: 'Point' | 'Polygon' | 'MultiPolygon';
coordinates: number[] | number[][][] | number[][][][];
};
};

export type OpenTopoResponse = {
Datasets: {
Dataset: {
name: string;
identifier: {
value: string;
};
alternateName: string;
url: string;
fileFormat: string;
description: string;
dateCreated: string;
temporalCoverage: string;
keywords: string;
spatialCoverage: {
geo: {
geojson: {
features: {
geometry: {
type: 'Polygon' | 'MultiPolygon';
coordinates: number[][][] | number[][][][];
};
}[];
};
};
};
};
}[];
};

export type ProcessedOpenTopoData = {
original: {
type: 'FeatureCollection';
features: OpenTopoFeature[];
};
centroids: {
type: 'FeatureCollection';
features: OpenTopoFeature[];
};
};

async function fetchOpenTopoData(): Promise<OpenTopoResponse> {
const res = await apiClient.get<OpenTopoResponse>('/recon-portal/opentopo/');
return res.data;
}

function preprocessData(data: OpenTopoResponse): ProcessedOpenTopoData {
const seenUrls = new Map<string, OpenTopoFeature>();
const result: ProcessedOpenTopoData['original'] = {
type: 'FeatureCollection',
features: [] as OpenTopoFeature[],
};
const centroidResult: ProcessedOpenTopoData['centroids'] = {
type: 'FeatureCollection',
features: [] as OpenTopoFeature[],
};
data.Datasets.forEach(({ Dataset: datasetInfo }) => {
const {
url,
fileFormat,
spatialCoverage,
identifier,
name,
alternateName,
dateCreated,
temporalCoverage,
keywords,
} = datasetInfo;

if (!url) return;

if (seenUrls.has(url)) {
const existingFeature = seenUrls.get(url);
if (existingFeature && fileFormat) {
existingFeature.properties.productAvailable += `, ${fileFormat}`;
}
} else {
let geometry = {} as OpenTopoFeature['geometry'];
if (spatialCoverage?.geo?.geojson?.features?.[0]?.geometry) {
geometry = spatialCoverage.geo.geojson.features[0].geometry as OpenTopoFeature['geometry'];
}

const feature: OpenTopoFeature = {
type: 'Feature',
properties: {
id: identifier.value,
name,
host: 'OpenTopo',
url,
doiUrl: url,
alternateName,
dateCreated,
temporalCoverage,
keywords,
productAvailable: fileFormat,
},
geometry,
};
seenUrls.set(url, feature);
result.features.push(feature);

// Generate centroid
if (geometry && (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon')) {
const geomShape = turf.centroid(feature as Feature);
const centroidFeature: OpenTopoFeature = {
type: 'Feature',
properties: {
id: identifier.value,
name,
host: 'OpenTopo',
alternateName,
doiUrl: url,
dateCreated,
keywords,
temporalCoverage,
url: `/datasetMetadata?otCollectionID=OT.${identifier.value.split('.').slice(1).join('.')}`,
productAvailable: fileFormat,
},
geometry: {
type: 'Point',
coordinates: (geomShape.geometry as Point).coordinates,
},
};
centroidResult.features.push(centroidFeature);
}
}
});
return { original: result, centroids: centroidResult };
}

export const getOpenTopoQuery = () => ({
queryKey: ['opentopo'],
queryFn: async () => {
const data = await fetchOpenTopoData();
return preprocessData(data);
},
staleTime: 1000 * 60 * 5, // 5 minute stale time
});

export function useGetOpenTopo() {
return useQuery(getOpenTopoQuery());
}

export default useGetOpenTopo;
12 changes: 12 additions & 0 deletions client/modules/reconportal/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"presets": [
[
"@nx/react/babel",
{
"runtime": "automatic",
"useBuiltIns": "usage"
}
]
],
"plugins": []
}
18 changes: 18 additions & 0 deletions client/modules/reconportal/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["plugin:@nx/react", "../../.eslintrc.base.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions client/modules/reconportal/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# reconportal

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test reconportal` to execute the unit tests via [Vitest](https://vitest.dev/).
20 changes: 20 additions & 0 deletions client/modules/reconportal/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "reconportal",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "modules/reconportal/src",
"projectType": "library",
"tags": [],
"targets": {
"lint": {
"executor": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"]
},
"test": {
"executor": "@nx/vite:test",
"outputs": ["{options.reportsDirectory}"],
"options": {
"reportsDirectory": "../../coverage/modules/reconportal"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.root {
color: #cc723e;
font-size: 16px;
}
13 changes: 13 additions & 0 deletions client/modules/reconportal/src/ReconPortal/ReconPortal.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { render } from '@client/test-fixtures';

import { ReconPortal } from './ReconPortal';

describe('ReconPortal', () => {

it('should render successfully', () => {
const { getByText } = render(<ReconPortal />);
expect(getByText(/Leaflet/gi)).toBeTruthy();
expect(getByText(/Placeholder/gi)).toBeTruthy();

});
});
11 changes: 11 additions & 0 deletions client/modules/reconportal/src/ReconPortal/ReconPortal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';
import styles from './ReconPortal.module.css';

export const ReconPortal: React.FC = () => {

return (
<div className={styles.root}>
Leaflet + Left-Sided Nav Placeholder
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.root {
color: #cc443e;
font-size: 16px;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { render } from '@client/test-fixtures';

import { ReconPortalHeader } from './ReconPortalHeader';

describe('ReconPortalHeader', () => {

it('should render successfully', () => {
const { getByText } = render(<ReconPortalHeader />);
expect(getByText(/Header Placeholder/gi)).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';
import styles from './ReconPortalHeader.module.css';

export const ReconPortalHeader: React.FC = () => {

return (
<div className={styles.root}>
Header Placeholder
</div>
);
};
2 changes: 2 additions & 0 deletions client/modules/reconportal/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './ReconPortal/ReconPortal';
export * from './ReconPortalHeader/ReconPortalHeader';
20 changes: 20 additions & 0 deletions client/modules/reconportal/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"allowJs": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"extends": "../../tsconfig.base.json"
}
Loading