Skip to content

Commit

Permalink
Mmigrate APIHooks and DataService to TypeScript (#1214)
Browse files Browse the repository at this point in the history
* Migrate DataService to TypeScript.

This takes a shortcut by using `any` in many of the type signatures.
There's not much we can really do about this, since most of these
functions are generic and either call `JSON.stringify()` on an arguments
or `resp.json()` on responses. For better type safety, we probably want
the wrapper functions that call these ones to have stricter type
annotations.

* Migrate APIHooks to TypeScript.

These use type assertions on the API responses, since we do not do any
runtime validation of data coming from the API. This also fixes a bug in
the ServiceDiscoveryResults type signatures, where it was expecting a
type of CategoryRefinement, but in reality we only had the data from a
Category (no Algolia-specific data in it).
  • Loading branch information
richardxia authored Jan 10, 2023
1 parent 9ec071a commit 607db76
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 25 deletions.
4 changes: 2 additions & 2 deletions app/components/listing/feedback/FeedbackForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ export const FeedbackForm = ({ service, resource, closeModal }: {
};

const [source, sourceId] = !service
? ['resources', resource.id]
: ['services', service.id];
? ['resources', resource.id] as const
: ['services', service.id] as const;

addFeedback(source, sourceId, feedback)
.then(() => {
Expand Down
13 changes: 7 additions & 6 deletions app/hooks/APIHooks.js → app/hooks/APIHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
import { useState, useEffect } from 'react';

import * as dataService from '../utils/DataService';
import type { Category, Eligibility } from '../models/Meta';

// TODO: Handle failure?

/** Make an API call to fetch all eligibilities for a given categoryID.
*
* Returns the list of eligibilities. Returns null until the request succeeds.
*/
export const useEligibilitiesForCategory = categoryID => {
const [eligibilities, setEligibilities] = useState(null);
export const useEligibilitiesForCategory = (categoryID: string | null): Eligibility[] | null => {
const [eligibilities, setEligibilities] = useState<Eligibility[] | null>(null);

useEffect(() => {
if (categoryID !== null) {
dataService.get(`/api/eligibilities?category_id=${categoryID}`).then(response => {
setEligibilities(response.eligibilities);
setEligibilities(response.eligibilities as Eligibility[]);
});
}
}, [categoryID]);
Expand All @@ -28,13 +29,13 @@ export const useEligibilitiesForCategory = categoryID => {
*
* Returns the list of categories. Returns null until the request succeeds.
*/
export const useSubcategoriesForCategory = categoryID => {
const [subcategories, setSubcategories] = useState(null);
export const useSubcategoriesForCategory = (categoryID: string | null) : Category[] | null => {
const [subcategories, setSubcategories] = useState<Category[] | null>(null);

useEffect(() => {
if (categoryID !== null) {
dataService.get(`/api/categories/subcategories?id=${categoryID}`).then(response => {
setSubcategories(response.categories);
setSubcategories(response.categories as Category[]);
});
}
}, [categoryID]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Loader } from 'components/ui';
import SearchResults from 'components/search/SearchResults/SearchResults';
import Sidebar from 'components/search/Sidebar/Sidebar';
import { Header } from 'components/search/Header/Header';
import { Category } from 'models/Meta';

import { useEligibilitiesForCategory, useSubcategoriesForCategory } from '../../hooks/APIHooks';
import config from '../../config';
Expand Down Expand Up @@ -104,7 +105,7 @@ const InnerServiceDiscoveryResults = ({
onSearchStateChange, searchRadius, setSearchRadius, expandList, setExpandList, userLatLng,
}: {
eligibilities: object[];
subcategories: ServiceCategory[];
subcategories: Category[];
categoryName: string;
categorySlug: string;
algoliaCategoryName: string;
Expand Down
24 changes: 16 additions & 8 deletions app/utils/DataService.js → app/utils/DataService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as _ from 'lodash/fp/object';
import * as _ from 'lodash';

function setAuthHeaders(resp) {
import type { VoteType } from '../components/listing/feedback/constants';

function setAuthHeaders(resp: Response): void {
const { headers } = resp;
if (headers.get('access-token') && headers.get('client')) {
// console.log('we would set new auth headers except for an API bug giving us invalid tokens',
Expand All @@ -16,7 +18,7 @@ function setAuthHeaders(resp) {
}
}

export function post(url, body, headers) {
export function post(url: RequestInfo | URL, body: any, headers?: HeadersInit): Promise<Response> {
let queryHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
Expand All @@ -36,7 +38,7 @@ export function post(url, body, headers) {
});
}

export function get(url, headers) {
export function get(url: RequestInfo | URL, headers?: HeadersInit): Promise<any> {
let queryHeaders = {
'Content-Type': 'application/json',
};
Expand All @@ -55,7 +57,7 @@ export function get(url, headers) {
});
}

export function put(url, body, headers) {
export function put(url: RequestInfo | URL, body: any, headers: HeadersInit): Promise<Response> {
let queryHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
Expand All @@ -75,7 +77,7 @@ export function put(url, body, headers) {
});
}

export function APIDelete(url, headers) {
export function APIDelete(url: RequestInfo | URL, headers: HeadersInit): Promise<void> {
let queryHeaders = {
'Content-Type': 'application/json',
};
Expand All @@ -92,8 +94,14 @@ export function APIDelete(url, headers) {
});
}

export const addFeedback = (source, sourceId, body) => (
interface FeedbackBody {
rating: VoteType;
tags: string[];
review: string;
}

export const addFeedback = (source: 'resources' | 'services', sourceId: number, body: FeedbackBody): Promise<Response> => (
post(`/api/${source}/${sourceId}/feedbacks`, body).then(res => res.json())
);

export const getResourceCount = () => get('/api/resources/count');
export const getResourceCount = (): Promise<number> => get('/api/resources/count');
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@types/chai": "^4.2.22",
"@types/enzyme": "^3.10.9",
"@types/google-map-react": "^2.1.3",
"@types/lodash": "^4.14.191",
"@types/mocha": "^9.0.0",
"@types/qs": "^6.9.6",
"@types/react": "^17.0.3",
Expand Down

0 comments on commit 607db76

Please sign in to comment.