Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
Empty file.
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.

29 changes: 29 additions & 0 deletions assignments/hackyourtemperature/__tests__/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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.

});

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).toHaveProperty("error", "City is not found");
Copy link

Choose a reason for hiding this comment

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

A more accurate statement is expect(response.body.weatherText).toBe("City is not found!");

});

it("Case3: (Empty 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.

Empty cityName should return 400 (Bad Request), not 500.
400 = client error (invalid input), 500 = server error (internal problem)

const response = await request.post("/weather").send({});
expect(response.status).toBe(500);
expect(response.body).toHaveProperty("error", "City is not found");
Copy link

Choose a reason for hiding this comment

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

A more accurate statement is expect(response.body.weatherText).toContain("Please provide a cityName");

});
});
44 changes: 44 additions & 0 deletions assignments/hackyourtemperature/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import express from "express";
import keys from "./sources/keys.js"; // to access it use keys.API_KEY
import fetch from "node-fetch";
const app = express();

export default app;
Copy link

Choose a reason for hiding this comment

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

Best practice is to list exports at the end of the file. Exporting before the app's routes are defined means that at the time of the export, the app doesn't include any routes, etc.
Since ES modules are evaluated asynchronously, your app still works before the app is imported in the server module, and all routes have been added, but it's better to follow the generally used pattern.


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." });
}

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

Choose a reason for hiding this comment

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

It doesn't make much difference from the perspective of learning how to work with APIs, but note that the instructions ask to use a different endpoint: https://api.openweathermap.org/data/2.5/**weather**.


fetchWeather(cityWeatherUrl);

async function fetchWeather(URL) {
try {
const response = await fetch(URL);
const data = await response.json();

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") {
throw new Error("City not found");
Copy link

Choose a reason for hiding this comment

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

This is a rather aggressive way of handling the situation. You could also do something like the following, which is more graceful:

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

}

const tempratureInCelsius = data.list[0].main.temp - 273.15; // Temperature in Celsius
Copy link

Choose a reason for hiding this comment

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

The API offers the option to specify which units the response should be using - whether standard, metric, or imperial. A better approach than manual conversion would be leveraging the built-in functionality of the API directly.


res.json({
weatherText: `Temperature in ${cityName}: ${tempratureInCelsius.toFixed(
2
)} °C`,
});
} catch (error) {
res.status(500).json({ error: "City is not found" });
Copy link

Choose a reason for hiding this comment

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

Nit: The 500 status code indicates an internal server error, not necessarily that the requested city was not found. I'd recommend a more generic message in this case, something like "Server error".

}
}
});

//
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: [],
};
28 changes: 28 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"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",
"express": "^5.1.0",
Copy link

Choose a reason for hiding this comment

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

Since Express is required at app runtime, it should be installed as a dependency, not just devDependency.

"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"
}
}
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.