Skip to content

Commit cddc42e

Browse files
committedOct 17, 2024
Added weather-data endpoint
1 parent 0ec3c40 commit cddc42e

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed
 

‎src/main.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import express, { Application } from "express";
22
import morgan from "morgan";
3-
import { getLocationData, getPublicFolderPath } from "./utils.js";
3+
import {
4+
getLocationData,
5+
getWeatherData,
6+
getPublicFolderPath,
7+
} from "./utils.js";
48
import cors from "cors";
59

610
const app: Application = express();
@@ -14,7 +18,9 @@ app.use(cors()); // enable cors to commmunicate with frontend
1418

1519
app.use(morgan("dev")); //Add logging for all endpoints
1620

17-
app.get("/weather-locs/:city", getLocationData);
21+
app.get("/cities/:city", getLocationData);
22+
23+
app.get("/cities/:city/weather-data", getWeatherData);
1824

1925
//Add error handler for all endpoints
2026
app.use((err, req, res, next) => {

‎src/utils.ts

+31-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { Request, Response, NextFunction } from "express";
22
import path, { dirname } from "path";
33
import { fileURLToPath } from "url";
4-
import axios from "axios";
4+
import axios, { AxiosResponse } from "axios";
55

66
const API_KEY: string = process.env.API_KEY;
7+
const LOCATION_URL: string = "https://geocode.maps.co/search";
8+
const WEATHER_URL: string = "https://api.weather.gov/points";
79

810
export function getPublicFolderPath(): string {
911
const __filename = fileURLToPath(import.meta.url); //abs path to filename
@@ -19,10 +21,37 @@ export async function getLocationData(
1921
const city: string = req.params.city;
2022
try {
2123
const response = await axios.get(
22-
`https://geocode.maps.co/search?q=${city}&api_key=${API_KEY}`
24+
`${LOCATION_URL}?q=${city}&api_key=${API_KEY}`
2325
);
2426
res.status(response.status).send(response.data);
2527
} catch (err) {
2628
next(err);
2729
}
2830
}
31+
32+
export function getWeatherData(
33+
req: Request,
34+
res: Response,
35+
next: NextFunction
36+
) {
37+
const city: string = req.params.city;
38+
axios
39+
.get(`${LOCATION_URL}?q=${city}&api_key=${API_KEY}`)
40+
.then((resp) => {
41+
const top_match = resp.data[0];
42+
return `${WEATHER_URL}/${top_match["lat"]},${top_match["lon"]}`;
43+
})
44+
.then((url) => {
45+
return axios.get(url);
46+
})
47+
.then((resp) => {
48+
const forecast_url = resp.data["properties"]["forecast"];
49+
return axios.get(forecast_url);
50+
})
51+
.then((resp) => {
52+
res.status(resp.status).send(resp.data["properties"]["periods"]);
53+
})
54+
.catch((err) => {
55+
next(err);
56+
});
57+
}

0 commit comments

Comments
 (0)
Please sign in to comment.