Skip to content

Commit

Permalink
feat: 現在の天気情報取得処理を新しいAPI方式に移行した(#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
h-yoshikawa44 committed Oct 22, 2023
1 parent a574919 commit 5341831
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { css } from '@emotion/react';
import Card from '@/components/common/Card';
import { colors } from '@/styles/constants';
import { raleway } from '@/styles/fonts';
import { convertKmToMile } from '@/utils/weather';

const title = {
visibility: 'Visibility',
Expand All @@ -23,7 +24,7 @@ const WeatherHighlightCommon: FC<Props> = ({ type, value }) => {
let roundValue;
if (value) {
if (type === 'visibility') {
roundValue = Math.round(value * 10) / 10;
roundValue = Math.round(convertKmToMile(value)) / 10;
} else if (type === 'airPressure') {
roundValue = Math.round(value);
}
Expand Down
16 changes: 8 additions & 8 deletions src/components/model/weather/WeatherTop/WeatherTop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import { convertCelsiusToFahrenheit } from '@/utils/weather';

type Props = {
today?: string;
weatherCode?: WeatherCode;
weatherIconSrc?: string;
weatherName?: string;
temperature?: number;
location?: string;
mode: TemperatureType;
Expand All @@ -28,7 +29,8 @@ type Props = {

const WeatherTop: FC<Props> = ({
today,
weatherCode,
weatherIconSrc,
weatherName,
temperature,
location,
mode,
Expand Down Expand Up @@ -59,11 +61,11 @@ const WeatherTop: FC<Props> = ({
<div css={[watherTopContents, watherTopContentLayout]}>
<div css={contentsBgImgBlock}>
<p css={contentsImgBlock}>
{weatherCode && (
{weatherIconSrc && weatherName && (
<Image
css={contentsImg}
src={weatherIcons[weatherCode]}
alt={weatherNames[weatherCode]}
src={weatherIconSrc}
alt={weatherName}
fill
/>
)}
Expand All @@ -73,9 +75,7 @@ const WeatherTop: FC<Props> = ({
<em>{roundTemp}</em>
{temperatureUnits[mode]}
</p>
<p css={contentsWeather}>
{weatherCode ? weatherNames[weatherCode] : '-'}
</p>
<p css={contentsWeather}>{weatherName ? weatherName : '-'}</p>
<div css={contentsSubTextBlock}>
<small css={contentsDate}>
Today -{' '}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,28 @@ import { FC } from 'react';
import { css } from '@emotion/react';
import { Navigation } from '@emotion-icons/material-rounded/Navigation';
import Card from '@/components/common/Card';
import { WindDirectionCompass } from '@/models/Weather';
import { windAngles } from '@/constants/weather';
import { colors } from '@/styles/constants';
import { raleway } from '@/styles/fonts';
import { convertDegToDirection, convertMpsToMph } from '@/utils/weather';

type Props = {
speed?: number;
compass?: WindDirectionCompass;
deg?: number;
};

const WeatherWindStatus: FC<Props> = ({ speed, compass }) => {
const WeatherWindStatus: FC<Props> = ({ speed, deg }) => {
return (
<Card>
<div css={weatherWindStatusLayout}>
<h4 css={weatherWindStatusTitle}>Wind status</h4>
<p css={weatherWindStatusSpeed}>
<em>{speed ? Math.round(speed) : '-'}</em>mph
<em>{speed ? Math.round(convertMpsToMph(speed)) : '-'}</em>mph
</p>
<p css={weatherWindStatusCompassBlock}>
<span css={compassBlockIconBg}>
<Navigation
css={compass ? compassBlockIcon(compass) : 'N'}
size={14}
/>
<Navigation css={compassBlockIcon(deg ?? 0)} size={14} />
</span>
<i css={compassBlockValue}>{compass}</i>
<i css={compassBlockValue}>{convertDegToDirection(deg ?? 0)}</i>
</p>
</div>
</Card>
Expand Down Expand Up @@ -79,10 +75,10 @@ const compassBlockIconBg = css`
border-radius: 50%;
`;

const compassBlockIcon = (compass: WindDirectionCompass) => {
const compassBlockIcon = (windDeg: number) => {
return css`
color: ${colors.gray6};
transform: rotate(${windAngles[compass]}deg);
transform: rotate(${windDeg}deg);
`;
};

Expand Down
27 changes: 15 additions & 12 deletions src/components/page/Home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ const Home: FC = () => {
} = useWeatherSetting();

const { isLoading, errorMessage, weather } = useWeather(
currentLocation?.woeId,
currentGeoLocation?.lat,
currentGeoLocation?.lon,
);

const {
Expand Down Expand Up @@ -63,8 +64,9 @@ const Home: FC = () => {
);
}

const today = weather?.consolidated_weather[0];
const week = weather?.consolidated_weather.slice(1);
const today = new Date(Date.now()).toLocaleDateString();
// TODO 後で正式なものにする
const week = [];

return (
<Fragment>
Expand All @@ -78,10 +80,11 @@ const Home: FC = () => {
}
>
<WeatherTop
today={today?.applicable_date}
weatherCode={today?.weather_state_abbr}
temperature={today?.the_temp}
location={weather?.title}
today={today}
weatherIconSrc={weather?.weatherIcon}
weatherName={weather?.weatherName}
temperature={weather?.temp}
location={weather?.city}
mode={temperatureMode}
handleLocationMenuOpen={handleLocationMenuOpen}
handleInitialCurrentLocation={handleInitialCurrentLocation}
Expand Down Expand Up @@ -140,17 +143,17 @@ const Home: FC = () => {
<div css={highlightSectionCardBlock}>
<div css={highlightSectionCardBlockLayout}>
<WeatherWindStatus
speed={today?.wind_speed}
compass={today?.wind_direction_compass}
speed={weather?.windSpeed}
deg={weather?.windDeg}
/>
<WeatherHumidity humidity={today?.humidity} />
<WeatherHumidity humidity={weather?.humidity} />
<WeatherHighlightCommon
type="visibility"
value={today?.visibility}
value={weather?.visibility}
/>
<WeatherHighlightCommon
type="airPressure"
value={today?.air_pressure}
value={weather?.airPressure}
/>
</div>
</div>
Expand Down
27 changes: 27 additions & 0 deletions src/domains/getCurrentWeather/getCurrentWeather.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Options } from 'ky-universal';
import { getExtendKy } from '@/config/ky';
import { isCurrentWeather } from '@/models/Weather';

const units = ['standard', 'metric', 'imperial'] as const;

export type CurrentWeatherQuery = {
/** 緯度 */
lat: number;
/** 経度 */
lon: number;
/** 測定単位 デフォルトは standard */
units?: (typeof units)[number];
};

export const getCurrentWeather = async (
options: Options & { searchParams: CurrentWeatherQuery },
) => {
const response = await getExtendKy('inner', options).get('weather');
const currentWeather = (await response.json()) as unknown[];

if (!isCurrentWeather(currentWeather)) {
throw Error('API type error');
}

return currentWeather;
};
3 changes: 3 additions & 0 deletions src/domains/getCurrentWeather/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { getCurrentWeather } from './getCurrentWeather';

export { getCurrentWeather };
15 changes: 8 additions & 7 deletions src/hooks/useWeather/useWeather.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { useState, useEffect } from 'react';
import { HTTPError } from 'ky-universal';
import { Weather } from '@/models/Weather';
import getWeather from '@/domains/getWeather';
import { CurrentWeather } from '@/models/Weather';
import { getCurrentWeather } from '@/domains/getCurrentWeather';

const httpErrorMessageText =
'Sorry, Failed to retrieve weather forecast information. Please take some time and try again.';
const errorMessageText = 'Unexpected data was retrieved.';

const useWeather = (woeId?: number) => {
const useWeather = (lat?: number, lon?: number) => {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [errorMessage, setErrorMessage] = useState<string>('');
const [weather, setWeather] = useState<Weather>();
const [weather, setWeather] = useState<CurrentWeather>();

useEffect(() => {
if (!woeId) {
if (!lat || !lon) {
return;
}
setIsLoading(true);
getWeather('inner', woeId)

getCurrentWeather({ searchParams: { lat, lon, units: 'metric' } })
.then((data) => {
setWeather(data);
setErrorMessage('');
Expand All @@ -32,7 +33,7 @@ const useWeather = (woeId?: number) => {
.finally(() => {
setIsLoading(false);
});
}, [woeId]);
}, [lat, lon]);

return { isLoading, errorMessage, weather };
};
Expand Down

0 comments on commit 5341831

Please sign in to comment.