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
2 changes: 2 additions & 0 deletions assignments/hackyourtemperature/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.env
8 changes: 8 additions & 0 deletions assignments/hackyourtemperature/.idea/.gitignore

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

12 changes: 12 additions & 0 deletions assignments/hackyourtemperature/.idea/hackyourtemperature.iml

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

8 changes: 8 additions & 0 deletions assignments/hackyourtemperature/.idea/modules.xml

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

6 changes: 6 additions & 0 deletions assignments/hackyourtemperature/.idea/vcs.xml

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

31 changes: 31 additions & 0 deletions assignments/hackyourtemperature/__tests__/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import supertest from "supertest";
import app from "../app.js";

const request = supertest(app);

describe("POST /weather", () => {
it("case1: (Valid city name) >>> should return weather data", async () => {
const response = await request
.post("/weather")
.send({ cityName: "London" });

expect(response.status).toBe(200);
Copy link

Choose a reason for hiding this comment

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

Should also check response.body.weatherText contains the requested city name and temperature.

expect(response.body).toContain("London");
// since the tempruture is not fixed, how should i do check it?
});

it("Case2: (Inavalid city name ) >>> should return 500 error", async () => {
Copy link

Choose a reason for hiding this comment

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

I'd argue that an invalid city is in fact a client error, not a server error. The response code I'd expect in this scenario is 404.

const response = await request
.post("/weather")
.send({ cityName: "Incorrect_CityName" });

expect(response.status).toBe(500);
expect(response.body).toBe("City is not found");
});

it("Case3: (Empty City Name) should return 400 error", async () => {
const response = await request.post("/weather").send({});
expect(response.status).toBe(400);
expect(response.body).toContain("Please provide a city name");
});
});
59 changes: 59 additions & 0 deletions assignments/hackyourtemperature/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import express from "express";
import keys from "./sources/keys.js"; // to access it use keys.API_KEY
import fetch from "node-fetch";
import dotenv from "dotenv";

dotenv.config();
const app = express();

app.use(express.json());

//GET request that sends the message [hello from backend to frontend!] to the client
app.get("/", (req, res) => {
res.send("Hello From Backend to Frontend");
});

// --------------5.1 Adding a POST request----------------
app.post("/weather", (req, res) => {
const { cityName } = req.body;
Copy link

Choose a reason for hiding this comment

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

It would be good to add input validation, making sure a cityName is provided in the request.

if (!cityName || typeof cityName !== "string" || !cityName.trim()) {
    return res.status(400).json({ weatherText: "Please provide a cityName." });
}

console.log("City name received", cityName);

if (!cityName || typeof cityName !== "string" || !cityName.trim()) {
return res.status(400).json({ weatherText: "City name is required" });
}

// const cityWeatherUrl = `http://api.openweathermap.org/data/2.5/forecast?q=${cityName}&appid=${keys.API_KEY}`;

const cityWeatherUrl = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(
cityName.trim()
)}&appid=${keys.API_KEY}&units=metric`;

fetchWeather(cityWeatherUrl);

async function fetchWeather(URL) {
try {
const response = await fetch(URL);
if (!response.ok) {
return res.status(500).json({ weatherText: "Response not ok" });
}
const data = await response.json();
console.log("Weather data received", data);

Copy link

Choose a reason for hiding this comment

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

A good practice when working with APIs is to check for !response.ok with correct error handling.

if (data.cod === "404") {
return res.status(404).json({ weatherText: "City not found" });
}

const tempratureInCelsius = data.main.temp;

res.json({
weatherText: `Temperature in ${cityName}: ${tempratureInCelsius.toFixed(
2
)} °C`,
});
} catch (error) {
res.status(500).json({ weatherText: error.message });
}
}
});

export default app;
13 changes: 13 additions & 0 deletions assignments/hackyourtemperature/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
presets: [
[
// This is a configuration, here we are telling babel what configuration to use
"@babel/preset-env",
{
targets: {
node: "current",
},
},
],
],
};
8 changes: 8 additions & 0 deletions assignments/hackyourtemperature/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default {
// Tells jest that any file that has 2 .'s in it and ends with either js or jsx should be run through the babel-jest transformer
transform: {
"^.+\\.jsx?$": "babel-jest",
},
// By default our `node_modules` folder is ignored by jest, this tells jest to transform those as well
transformIgnorePatterns: [],
};
29 changes: 29 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "hackyourtemperature",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "jest",
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/preset-env": "^7.28.5",
"babel-jest": "^30.2.0",
"jest": "^30.2.0",
"nodemon": "^3.1.10",
"supertest": "^7.1.4"
},
"dependencies": {
"dotenv": "^17.2.3",
"express-handlebars": "^8.0.3",
"node-fetch": "^3.3.2",
"express": "^5.1.0"

}
}
5 changes: 5 additions & 0 deletions assignments/hackyourtemperature/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import app from "./app.js";

app.listen(3000, () => {
console.log("Server on Port 3000 is running");
});
1 change: 1 addition & 0 deletions assignments/hackyourtemperature/sources/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default { API_KEY: "d63cf1893cfbd168dfb340b341a8c03e" };
Copy link

Choose a reason for hiding this comment

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

Hardcoding API keys in source code is acceptable for learning purposes, but in production, you should use environment variables (process.env.API_KEY) and add this file to .gitignore.