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

feat: text search google api 마이그레이션 #202

Merged
merged 3 commits into from
Oct 16, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function GET(request: NextRequest) {
const requestHeaders = new Headers(request.headers);

const query = searchParams.get('query');
const nextCursor = searchParams.get('nextCursor');

if (!query) {
return NextResponse.json(null, {
Expand All @@ -27,6 +28,8 @@ export async function GET(request: NextRequest) {
key: process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY,
query,
region: 'KR',
opennow: false,
pagetoken: nextCursor ?? undefined,
},
});

Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions src/components/detail/PlaceDetailWindow/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import useRenderToast from '@/hooks/useRenderToast';
import { paramsSerializer } from '@/lib/apis';
import { CloseIcon, ShareIcon } from '@/lib/assets/icons';
import { PlacesWithSearchResult } from '@/lib/types/search';
import { PlacesWithDetailSearchResult } from '@/lib/types/search';

import styles from './index.module.scss';

Expand All @@ -47,7 +47,7 @@
isVisible: boolean;
isLoading: boolean;
onClose: () => void;
placeDetail: PlacesWithSearchResult<true> | null;
placeDetail: PlacesWithDetailSearchResult<true> | null;
};

function PlaceDetailWindow({
Expand Down Expand Up @@ -78,7 +78,7 @@
} catch (error) {
renderToast('URL 복사에 실패했습니다.', { type: 'error' });
}
}, [placeDetail?.place_id, placeDetail?.name]);

Check warning on line 81 in src/components/detail/PlaceDetailWindow/index.tsx

View workflow job for this annotation

GitHub Actions / check unit test & lint

React Hook useCallback has missing dependencies: 'params' and 'renderToast'. Either include them or remove the dependency array

const displayDetailInfoText = useCallback(() => {
if (googleReviewCount < 3) {
Expand Down
8 changes: 4 additions & 4 deletions src/components/detail/PlaceDetailWindowContainer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import useGetPlaceDetails from '@/hooks/maps/useGetPlaceDetails';
import useGetSearchBlog from '@/hooks/queries/useGetSearchBlog';
import { PlaceResult } from '@/lib/types/google.maps';
import { PlacesWithSearchResult } from '@/lib/types/search';
import { PlaceDetailResult } from '@/lib/types/google.maps';
import { PlacesWithDetailSearchResult } from '@/lib/types/search';
import usePlaceDetailWindowStore from '@/stores/placeDetailWindow';

import PlaceDetailWindow from '../PlaceDetailWindow';
Expand All @@ -16,7 +16,7 @@
} = usePlaceDetailWindowStore(['isOpenPlaceDetailWindow', 'onClosePlaceDetailWindow', 'placeId']);

const { data: placesWithSearchResult, isLoading } = useGetSearchBlog<true>({
placesResult: [placeDetailsState as PlaceResult],
placesResult: [placeDetailsState as PlaceDetailResult],
includePost: true,
enabled: !!placeDetailsState,
});
Expand All @@ -30,13 +30,13 @@
if (placeId) {
onGetPlaceDetails(placeId);
}
}, [placeId]);

Check warning on line 33 in src/components/detail/PlaceDetailWindowContainer/index.tsx

View workflow job for this annotation

GitHub Actions / check unit test & lint

React Hook useEffect has a missing dependency: 'onGetPlaceDetails'. Either include it or remove the dependency array

return (
<PlaceDetailWindow
isLoading={isLoading}
isVisible={isOpenPlaceDetailWindow}
placeDetail={placesWithSearchResult?.[0] as PlacesWithSearchResult<true> | null}
placeDetail={placesWithSearchResult?.[0] as PlacesWithDetailSearchResult<true> | null}
onClose={onCloseDetailWindow}
/>
);
Expand Down
47 changes: 36 additions & 11 deletions src/components/map/LoadMapContainer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useEffect } from 'react';
import { useEffect, useState } from 'react';

import { Status } from '@googlemaps/google-maps-services-js';
import { useGoogleMap } from '@react-google-maps/api';

import PlaceDetailWindowContainer from '@/components/detail/PlaceDetailWindowContainer';
import useTextSearch from '@/hooks/maps/useTextSearch';
import useGetGoogleSearch from '@/hooks/queries/useGetGoogleSearch';
import usePlaceDetailWindowStore from '@/stores/placeDetailWindow';
import useRecentSearchStore from '@/stores/recentSearch';

Expand All @@ -19,28 +20,28 @@

function LoadMapContainer({ defaultCountryCode, defaultPlaceId, defaultPlaceName }: Props) {
const map = useGoogleMap();
const [searchKeyword, setSearchKeyword] = useState<string>('');

const { addRecentSearch: saveNextKeyword } = useRecentSearchStore(['addRecentSearch']);
const { onOpenPlaceDetailWindow } = usePlaceDetailWindowStore(['onOpenPlaceDetailWindow']);

const {
placesResult, onTextSearch, isZeroResult,
} = useTextSearch(map);
query: { data: places, isSuccess }, refState,
} = useGetGoogleSearch({ keyword: searchKeyword });

const handleSubmit = (keyword: string) => {
onTextSearch({ query: keyword });
setSearchKeyword(keyword);
saveNextKeyword(keyword);
};

useEffect(() => {
if (defaultPlaceId && defaultPlaceName && map) {
onTextSearch({ query: defaultPlaceName });

onOpenPlaceDetailWindow({
placeId: defaultPlaceId,
placeName: defaultPlaceName,
});
}
}, [defaultPlaceId, defaultPlaceName, map]);

Check warning on line 44 in src/components/map/LoadMapContainer/index.tsx

View workflow job for this annotation

GitHub Actions / check unit test & lint

React Hook useEffect has a missing dependency: 'onOpenPlaceDetailWindow'. Either include it or remove the dependency array

useEffect(() => {
if (!map) {
Expand All @@ -60,15 +61,39 @@
});
}, [defaultCountryCode, map]);

useEffect(() => {
if (
!map
|| !isSuccess
|| places?.pages?.[0]?.status === Status.ZERO_RESULTS
|| !places?.pages.length
) {
return;
}

const markerBounds = new google.maps.LatLngBounds();

places.pages.flatMap((place) => place.results).forEach((place) => {
if (place?.geometry?.location) {
markerBounds.extend(place.geometry.location);
}
});

map.fitBounds(markerBounds);
}, [map, isSuccess, places]);

return (
<>
<SearchInput onSubmit={handleSubmit} />
{placesResult.map((place) => (
<PlaceResultMarker key={place.place_id} place={place} />
{places?.pages?.map((placeResult) => (
placeResult.results.map((place) => (
<PlaceResultMarker key={place.place_id} place={place} />
))
))}
<PlaceBottomSheet
placesResult={placesResult}
isZeroResult={isZeroResult}
places={places}
refState={refState}
isSuccess={isSuccess}
/>
<PlaceDetailWindowContainer />
</>
Expand Down
54 changes: 20 additions & 34 deletions src/components/map/PlaceBottomSheet/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { useEffect, useState } from 'react';
import { BottomSheet } from 'react-spring-bottom-sheet';

import { checkEmpty } from '@nf-team/core';
import { Status } from '@googlemaps/google-maps-services-js';
import { checkEmpty, isEmpty } from '@nf-team/core';
import { InfiniteData } from '@tanstack/react-query';

import Button from '@/components/common/Button';
import Spinner from '@/components/common/Spinner';
import useGetSearchBlog from '@/hooks/queries/useGetSearchBlog';
import useIntersectionObserver from '@/hooks/useIntersectionObserver';
import { PlaceResult } from '@/lib/types/google.maps';
import { SelectedPlace } from '@/lib/types/search';
import usePlaceStore from '@/stores/place';
import { InfiniteRefState } from '@/lib/types';
import { TextSearchPlace } from '@/lib/types/google.maps';
import { PlacesWithSearchResult, SelectedPlace } from '@/lib/types/search';
import usePlaceDetailWindowStore from '@/stores/placeDetailWindow';
import { targetFalseThenValue } from '@/utils';

Expand All @@ -18,52 +18,38 @@ import PlaceBottomSheetItem from '../PlaceBottomSheetItem';
import styles from './index.module.scss';

type Props = {
placesResult: PlaceResult[];
isZeroResult?: boolean;
places?: InfiniteData<TextSearchPlace>;
refState: InfiniteRefState<HTMLDivElement>;
isSuccess: boolean;
};

function PlaceBottomSheet({ placesResult, isZeroResult }: Props) {
const [isOpen, setIsOpen] = useState<boolean>(false);

const { pagination: placePagination } = usePlaceStore(['pagination']);

const refState = useIntersectionObserver<HTMLDivElement>({
isRoot: true,
fetchNextPage: placePagination?.fetchNextPage,
hasNextPage: placePagination?.hasNextPage,
intersectionOptions: {
rootMargin: '80px',
},
});
function PlaceBottomSheet({ places, refState, isSuccess }: Props) {
const placesResult = checkEmpty(places?.pages.flatMap((value) => value.results));
const isZeroResult = isSuccess && (
isEmpty(placesResult) || places?.pages?.[0].status === Status.ZERO_RESULTS
);

const {
onOpenPlaceDetailWindow, isOpenPlaceDetailWindow,
} = usePlaceDetailWindowStore(['onOpenPlaceDetailWindow', 'isOpenPlaceDetailWindow']);

// TODO - 마이그레이션
const {
data: placesWithSearchResult, isFetching,
data: placesWithSearchResult, isFetching, isSuccess: isSuccessPlacesWithSearchResult,
} = useGetSearchBlog<false>({
placesResult,
includePost: false,
enabled: !!placesResult?.length && !isZeroResult,
enabled: !isEmpty(placesResult),
});

const onClickPlaceItem = (
selectedPlaceForm: SelectedPlace,
) => onOpenPlaceDetailWindow(selectedPlaceForm);

useEffect(() => {
if (placesResult?.length || isZeroResult) {
setIsOpen(true);
return;
}

setIsOpen(false);
}, [placesResult?.length, isZeroResult]);

return (
<BottomSheet
open={isOpen && !isOpenPlaceDetailWindow}
open={!isOpenPlaceDetailWindow
&& (isZeroResult || isSuccessPlacesWithSearchResult || isFetching)}
blocking={false}
defaultSnap={({ maxHeight }) => (isZeroResult ? 168 : maxHeight / 2)}
snapPoints={({ maxHeight }) => (isZeroResult ? [168] : [
Expand All @@ -90,7 +76,7 @@ function PlaceBottomSheet({ placesResult, isZeroResult }: Props) {
!(placesWithSearchResult.length - 1 === index),
)(refState.lastItemRef)
}
place={place}
place={place as PlacesWithSearchResult}
onClick={onClickPlaceItem}
/>
))}
Expand Down
2 changes: 1 addition & 1 deletion src/components/map/PlaceResultMarker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function PlaceResultMarker({ place }: Props) {
icon={icon}
onClick={onClickMarker}
title={place.name}
position={place.geometry?.location as google.maps.LatLng}
position={place.geometry?.location}
/>
);
}
Expand Down
8 changes: 4 additions & 4 deletions src/hooks/maps/useGetPlaceDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
import { useGoogleMap } from '@react-google-maps/api';

import useRenderToast from '@/hooks/useRenderToast';
import { PlaceResult } from '@/lib/types/google.maps';
import { PlaceDetailResult } from '@/lib/types/google.maps';

const hasPlaceLocation = (
placeDetail: google.maps.places.PlaceResult | null,
): placeDetail is PlaceResult => Boolean(placeDetail?.geometry?.location);
): placeDetail is PlaceDetailResult => Boolean(placeDetail?.geometry?.location);

function useGetPlaceDetails():
[PlaceResult | null, (placeId: string) => void, () => void] {
[PlaceDetailResult | null, (placeId: string) => void, () => void] {
const map = useGoogleMap();
const renderToast = useRenderToast();
const [
placeDetailsState, setPlaceDetailsState,
] = useState<PlaceResult | null>(null);
] = useState<PlaceDetailResult | null>(null);

const onGetPlaceDetails = useCallback((placeId: string) => {
if (!map) {
Expand Down Expand Up @@ -43,7 +43,7 @@

renderToast('다시 시도해주세요.', { type: 'error' });
});
}, [map]);

Check warning on line 46 in src/hooks/maps/useGetPlaceDetails.ts

View workflow job for this annotation

GitHub Actions / check unit test & lint

React Hook useCallback has a missing dependency: 'renderToast'. Either include it or remove the dependency array

const resetPlaceDetails = useCallback(() => setPlaceDetailsState(null), []);

Expand Down
23 changes: 1 addition & 22 deletions src/hooks/maps/useTextSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
) {
if (status === google.maps.places.PlacesServiceStatus.OK && places?.length) {
setIsZeroResult(false);
addPlaces(filteredPlaces(places));
addPlaces(filteredPlaces(places as any) as any);

Check warning on line 23 in src/hooks/maps/useTextSearch.ts

View workflow job for this annotation

GitHub Actions / check unit test & lint

Unexpected any. Specify a different type

Check warning on line 23 in src/hooks/maps/useTextSearch.ts

View workflow job for this annotation

GitHub Actions / check unit test & lint

Unexpected any. Specify a different type
setPagination({
hasNextPage: pagination?.hasNextPage,
fetchNextPage: () => {
Expand All @@ -46,7 +46,7 @@
resetPlaces();
placeService?.textSearch(request, textSearchAction);
}
}, [placeService]);

Check warning on line 49 in src/hooks/maps/useTextSearch.ts

View workflow job for this annotation

GitHub Actions / check unit test & lint

React Hook useCallback has missing dependencies: 'resetPlaces' and 'textSearchAction'. Either include them or remove the dependency array

useEffect(() => {
if (map) {
Expand All @@ -54,27 +54,6 @@
}
}, [map]);

useEffect(() => {
if (!placesResult.length || !map || isZeroResult) {
return;
}

const markerBounds = new google.maps.LatLngBounds();

placesResult.forEach((place) => {
if (place?.geometry?.viewport) {
markerBounds.union(place.geometry.viewport);
}

if (place?.geometry?.location) {
markerBounds.extend(place.geometry.location);
}
});

map.fitBounds(markerBounds);
map.fitBounds(markerBounds);
}, [placesResult, map, isZeroResult]);

return {
onTextSearch,
placesResult,
Expand Down
33 changes: 30 additions & 3 deletions src/hooks/queries/useGetGoogleSearch.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,40 @@
import { useQuery } from '@tanstack/react-query';
import { checkEmpty } from '@nf-team/core';
import { useInfiniteQuery } from '@tanstack/react-query';

import { fetchGoogleSearch } from '@/lib/apis/search';
import { TextSearchPlace } from '@/lib/types/google.maps';
import { filteredPlaces } from '@/utils';

import useIntersectionObserver from '../useIntersectionObserver';

function useGetGoogleSearch({ keyword }: { keyword: string; }) {
const query = useQuery([keyword], () => fetchGoogleSearch({ keyword }), {
const query = useInfiniteQuery<TextSearchPlace>(['googleSearch', keyword], ({ pageParam }) => fetchGoogleSearch({ keyword, nextCursor: pageParam }), {
enabled: !!keyword,
getNextPageParam: ({ next_page_token }) => next_page_token,
select: (response) => ({
...response,
pages: checkEmpty(response?.pages).map((places) => ({
...places,
results: filteredPlaces(checkEmpty(places?.results)),
})),
}),
});

const { hasNextPage, fetchNextPage } = query;

const refState = useIntersectionObserver<HTMLDivElement>({
isRoot: true,
fetchNextPage,
hasNextPage,
intersectionOptions: {
rootMargin: '80px',
},
});

return query;
return {
query,
refState,
};
}

export default useGetGoogleSearch;
22 changes: 19 additions & 3 deletions src/hooks/queries/useGetSearchBlog.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
import { useMemo } from 'react';

import { checkEmpty } from '@nf-team/core';
import { useQuery } from '@tanstack/react-query';

import { fetchAllSettledSearchBlogs } from '@/lib/apis/search';
import { PlaceResult } from '@/lib/types/google.maps';
import { PlaceDetailResult, PlaceResult } from '@/lib/types/google.maps';

const TEN_MINUTES = 600000;

const isPlaceDetail = <T = boolean>(
placesResult: PlaceDetailResult[] | PlaceResult[],
includePost?: T,
): placesResult is PlaceDetailResult[] => Boolean(includePost) === true;

function useGetSearchBlog<T = boolean>({
placesResult, includePost, enabled,
}: { placesResult: PlaceResult[]; includePost?: T; enabled?: boolean; }) {
const placeName = placesResult.filter((place) => place).map((place) => place?.name);
}: {
placesResult: PlaceDetailResult[] | PlaceResult[];
includePost?: T;
enabled?: boolean; }) {
const placeName = useMemo(() => {
if (isPlaceDetail<T>(placesResult, includePost)) {
return placesResult.filter((place) => place).map((place) => place?.name);
}

return placesResult.filter((place) => place).map((place) => place?.name);
}, [placesResult, includePost]);

const query = useQuery(
[{ placeName, includePost }],
Expand Down
Loading
Loading