Skip to content

Samira w2 node.js #12

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 16 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ yarn-error.log
*.bkp

week3/prep-exercise/server-demo/

.env
49 changes: 49 additions & 0 deletions assignments/hackyourtemperature/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Import necessary modules
import express from 'express';
import fetch from 'node-fetch';
import keys from './sources/keys.js';

// Initialize Express app
const app = express();

// Middleware to parse JSON request bodies
app.use(express.json());

// Define a simple GET route
app.get('/', async (req, res) => {
res.send("Hello from backend to frontend")
});

// Post route to fetch weather data
app.post('/weather', async (req, res) => {
// Extract city name from request body
const { cityName } = req.body;

// Validate the request
if (!cityName) {
return res.status(400).json({ weatherText: "City name is required" });
}
Copy link

Choose a reason for hiding this comment

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

Same here, the comment in its own line. Also try to use chaining to improve code readability

    // Validate the request
    if (!cityName) {
        return res.status(400)
            .json({ message: "City name is required" });
    }

try {
// Fetch weather data from OpenWeatherMap API using provided city name and API key
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${keys.API_KEY}&units=metric`
Copy link

Choose a reason for hiding this comment

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

Since you have the BASE_URL, you use it here.

);
const data = await response.json();


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

// return fetched weather data
res.json({
temperature: data.main.temp,
weatherText: `The temperature in ${data.name} is ${data.main.temp}°C`

});
Copy link

Choose a reason for hiding this comment

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

In the instructions in week2/MAKEME.md, the return object should be

{
    weatherText: <message>
}


} catch (error) {
res.status(500).json({ weatherText: "Server error" });
}
});
export default app;
36 changes: 36 additions & 0 deletions assignments/hackyourtemperature/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Import required modules for testing
import request from "supertest";
import app from "./app.js";

// Define test suite for POST /weather route
describe("POST /weather" , () => {
it("should return weather data for a valid city", async () => {
const response = await request(app)
.post('/weather')
.send({ cityName: "London" });

expect(response.status).toBe(200);
expect(response.body).toHaveProperty("temperature");
expect(response.body.temperature).toBeGreaterThan(-50);
expect(response.body.temperature).toBeLessThan(60);
});

it("should return an error for an invalid city", async () => {
const response = await request(app)
.post('/weather')
.send({ cityName: "InvalidCity" });

expect(response.status).toBe(404);
expect(response.body).toHaveProperty("weatherText", "City is not found");
});

it("should return an error for an empty city", async () => {
const response = await request(app)
.post('/weather')
.send({ cityName: "" });

expect(response.status).toBe(400);
expect(response.body).toHaveProperty("weatherText", "City name is required");
});
});

32 changes: 32 additions & 0 deletions assignments/hackyourtemperature/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "hackyourtemperature",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"test": "jest",
"start": "node server.js"
},
"keywords": [],
"type": "module",
"author": "[email protected]",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-handlebars": "^8.0.1",
"node-fetch": "^2.7.0"
},
"devDependencies": {
"@babel/core": "^7.26.9",
"@babel/preset-env": "^7.26.9",
"babel-jest": "^29.7.0",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"supertest": "^7.0.0",
"ts-jest": "^29.2.6"
},
"directories": {
"test": "tests"
},
"description": ""
}
8 changes: 8 additions & 0 deletions assignments/hackyourtemperature/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import app from './app.js';

const PORT = 3000;

// Start the server on the specified port
app.listen(PORT, () => {
console.log(`Server is runnig on port ${PORT}`);
});
7 changes: 7 additions & 0 deletions assignments/hackyourtemperature/sources/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import dotenv from "dotenv";
Copy link

Choose a reason for hiding this comment

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

Like a pro!

dotenv.config();

export default {
BASE_URL:process.env.BASE_URL,
API_KEY:process.env.API_KEY,
};