Skip to content
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
32 changes: 32 additions & 0 deletions services/backend/api/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,40 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .models import Condition, Forecast
from typing import List, Optional
from datetime import datetime, timedelta
import random

app = FastAPI()

origins = ["http://localhost", "http://localhost:3000"]

app.add_middleware(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The frontend is technically located at a different origin so we have to enable CORS so the requests will be allowed. More here.

CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


@app.get("/")
async def get_root():
return {"data": "I am a WeatherApp"}


@app.get("/forecast/{location}", response_model=List[Forecast])
async def get_forecast_by_location(
location: str, start_date: Optional[datetime] = None, days: int = 5
):
if not start_date:
start_date = datetime.now().date()
forecasts = []
for delta in range(days):
forecast_date = start_date + timedelta(days=delta)
# Just get a random condition and temp
condition = random.choice(list(Condition))
temp = round(random.uniform(23, 105), 1)
forecast = Forecast(date=forecast_date, condition=condition, temp=temp)
forecasts.append(forecast)
return forecasts
25 changes: 25 additions & 0 deletions services/backend/api/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from pydantic import BaseModel
from datetime import date
from enum import Enum


class Condition(str, Enum):
sunny = "sunny"
cloudy = "cloudy"
partial_cloudy = "partial-cloudy"
partial_sunny = "partial-sunny"
windy = "windy"
lightning = "lightning"
snow = "snow"
rain = "rain"
light_right = "light-rain"
heavy_rain = "heavy-rain"


class Forecast(BaseModel):
date: date
condition: Condition
temp: float

class Config:
use_enum_values = True
11 changes: 11 additions & 0 deletions services/backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,14 @@
def test_root():
response = test_app.get("/")
assert response.status_code == 200


def test_forecast():
test_location = "San Francisco, CA"
days = 10
response = test_app.get(f"/forecast/{test_location}?days={days}")
assert (
response.status_code == 200
), f"Expected response 200, got {response.status_code}: {response.reason}."
data = response.json()
assert len(data) == days
52 changes: 26 additions & 26 deletions services/frontend/src/components/WeatherForecast.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
import WeatherWidgetContainer from "./WeatherWidgetContainer";
import Header from "./Header";
import { useState } from "react";
import { useState, useEffect } from "react";
import PropTypes from "prop-types";

export const WeatherForecast = ({ locationData, defaultExpanded }) => {
// Placeholder weather data
const weatherData = [
{
temp: 51,
cond: "cloudy",
},
{
temp: 48,
cond: "rain",
},
{
temp: 58,
cond: "windy",
},
{
temp: 62,
cond: "partial-cloudy",
},
{
temp: 71,
cond: "sunny",
},
];

const [isExpanded, setIsExpanded] = useState(defaultExpanded);
const [weatherData, setWeatherData] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);

useEffect(() => {
fetch(
`http://localhost:8000/forecast/${locationData.city}, ${locationData.state}`
)
.then((res) => res.json())
.then(
(result) => {
// console.log(result);
setWeatherData(result);
setIsLoaded(true);
},
(error) => {
console.log(error);
// TODO: Add isError state handling
}
);
}, [locationData]);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffect accepts a final argument that describes its dependencies. Anytime a dependency is updated the effect will run again. In this case we just need this to run once when the container mounts so we shouldn't have any dependencies. However, since we're using locationData in our API call we need to include it as a dependency (even if we don't expect it to change inside the container)


const toggleExpanded = () => {
setIsExpanded(!isExpanded);
Expand All @@ -42,7 +38,11 @@ export const WeatherForecast = ({ locationData, defaultExpanded }) => {
onClick={toggleExpanded}
>
<Header city={locationData.city} state={locationData.state} />
<WeatherWidgetContainer weatherObjArray={weatherData} />
{isLoaded ? (
<WeatherWidgetContainer weatherObjArray={weatherData} />
) : (
<p>"Loading..."</p>
)}
</div>
) : (
<div
Expand Down
6 changes: 3 additions & 3 deletions services/frontend/src/components/WeatherWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
faSlash,
} from "@fortawesome/free-solid-svg-icons";

const WeatherWidget = ({ temp, cond }) => {
const WeatherWidget = ({ temp, condition }) => {
const getIconFromString = (conditionString) => {
let returnVal;
switch (conditionString) {
Expand Down Expand Up @@ -53,7 +53,7 @@ const WeatherWidget = ({ temp, cond }) => {
<div className="px-5 text-2xl md:text-6xl">
<div>
<h1>
<FontAwesomeIcon icon={getIconFromString(cond)} />
<FontAwesomeIcon icon={getIconFromString(condition)} />
</h1>
</div>
<div className="text-2xl md:text-4xl">
Expand All @@ -67,7 +67,7 @@ const WeatherWidget = ({ temp, cond }) => {

WeatherWidget.propTypes = {
temp: PropTypes.number,
cond: PropTypes.string,
condition: PropTypes.string,
};

export default WeatherWidget;
14 changes: 4 additions & 10 deletions services/frontend/src/components/WeatherWidgetContainer.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import PropTypes from "prop-types";
import WeatherWidget from "./WeatherWidget";

const WeatherWidgetContainer = ({ weatherObjArray, widgetCount }) => {
const WeatherWidgetContainer = ({ weatherObjArray }) => {
const createWeatherWidgets = (objArray) => {
const widgetArray = [];
for (let index = 0; index < widgetCount; index++) {
let obj = objArray[index];
if (!obj) {
console.log(`Object ${index} was missing!`);
obj = { temp: null, cond: null };
}
for (const [index, obj] of objArray.entries()) {
const widget = (
<WeatherWidget key={index} temp={obj.temp} cond={obj.cond} />
<WeatherWidget key={index} temp={obj.temp} condition={obj.condition} />
);
widgetArray.push(widget);
}
Expand All @@ -29,10 +24,9 @@ WeatherWidgetContainer.propTypes = {
weatherObjArray: PropTypes.arrayOf(
PropTypes.shape({
temp: PropTypes.number,
cond: PropTypes.string,
condition: PropTypes.string,
})
),
widgetCount: PropTypes.number,
};

WeatherWidgetContainer.defaultProps = {
Expand Down