Skip to content

Rizan node.js w2 #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
28 changes: 28 additions & 0 deletions assignments/HackYourTemperature/__tests__/app.test.js

Choose a reason for hiding this comment

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

This has a few issues.

  1. Missing await on request.post("/weather")

  2. The test is calling request.post("/weather") but does not await it. It should be await request(app).post("/weather").
    Incorrect weatherText check in 404 case

  3. Your test expects response.body.weatherText to be "city is not found!", but if your server returns { message: "city is not found!" }, then response.body.weatherText will be undefined. Make sure your test matches the actual response structure.

  4. Hardcoded weather response format

The test expects "The temperature in Amsterdam is" but weather responses can vary. If your API returns structured JSON with temperature and description, test for that instead of checking a sentence.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import request from "supertest";
import app from "../server.js";

describe("POST /weather", () => {
it("should return a 400 error if cityName is missing", async () => {
const response = await request.post("/weather").send({});
expect(response.status).toBe(400);
expect(response.body).toEqual({ message: "City name is required." });
});

it("should return a 404 error if cityName is not found", async () => {
const response = await request
.post("/weather")
.send({ cityName: "invalidCity" });
expect(response.status).toBe(404);
expect(response.body.weatherText).toBe("city is not found!");
});

it("should return a valid weather response for a real city", async () => {
const response = await request(app)
.post("/weather")
.send({ cityName: "Amsterdam" });
expect(response.status).toBe(200);
expect(response.body.weatherText).toContain(
"The temperature in Amsterdam is"
);
});
});
47 changes: 47 additions & 0 deletions assignments/HackYourTemperature/app.js

Choose a reason for hiding this comment

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

If keys.API_KEY is undefined, your API request will fail silently.
You should return a 500 error if the key is missing.

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import express from "express";
import keys from "./sources/keys.js";
import fetch from "node-fetch";

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
res.send("hello from backend to frontend!");
});

app.post("/weather", async (req, res) => {
const cityName = req.body.cityName;

if (!cityName) {
return res.status(400).json({ message: "City name is required." });
}
const API_KEY = keys.API_KEY;
if (!API_KEY) {
return res.status(500).json({ message: "API key is missing." });
}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}&units=metric`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
if (data.cod === "404") {
return res.status(404).json({ weatherText: "city is not found!" });
}

const temperature = data.main.temp;
res.status(200).json({
weatherText: `The temperature in ${cityName} is ${temperature}°C`,
});
} catch (error) {
console.error("Error fetching weather data:", error.message);
res
.status(500)
.json({ message: "An error occurred while fetching weather data." });
}
});

export default app;
4 changes: 4 additions & 0 deletions assignments/HackYourTemperature/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: ["@babel/plugin-transform-modules-commonjs"],
};
3 changes: 3 additions & 0 deletions assignments/HackYourTemperature/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
transformIgnorePatterns: ["/node_modules/(?!node-fetch)"],
};
25 changes: 25 additions & 0 deletions assignments/HackYourTemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "hackyourtemperature",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-handlebars": "^8.0.1",
"node-fetch": "^3.3.2"
},
"type": "module",
"devDependencies": {
"@babel/preset-env": "^7.26.9",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"supertest": "^7.0.0"
}
}
7 changes: 7 additions & 0 deletions assignments/HackYourTemperature/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import app from "./app.js";

const PORT = 3000;

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
1 change: 1 addition & 0 deletions assignments/HackYourTemperature/sources/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API_KEY: "6c6488cdc94811312595951b156b69ba",
5 changes: 5 additions & 0 deletions assignments/HackYourTemperature/sources/keys.js

Choose a reason for hiding this comment

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

exposing an API key in your source code is a security risk.

Anyone can steal and misuse it.

The best practice is to hide the API key.

npm install dotenv

Move API key to a .env file (create this in your project root):

and write in it:

API_KEY=afc0f7157bda937505e237c68802afa5

then you can import the dotenv to securely import that api key. Something like this below.

import dotenv from 'dotenv';
dotenv.config();

export const keys = {
API_KEY: process.env.API_KEY
};

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import dotenv from "dotenv";
dotenv.config();
export const keys = {
API_KEY: process.env.API_KEY,
};
Empty file added cd
Empty file.